带有 "main" 和浮点数到非浮点数的对象列
Object column with "main" and float numbers to non float numbers
希望有人能帮助我
我有
数量
对象
名字 1
主要
名字2
490348,0
名字3
237928,0
df 类型是“对象”列的对象
我需要摆脱浮点数并将它们变成整数。
但是我得到一个错误“无法将 float NaN 转换为整数”。
非常感谢!!!
您可以尝试通过 pd.to_numeric()
+np.where()
:
import numpy as np
s=pd.to_numeric(df['Object'].replace(',','',regex=True),errors='coerce')
df['Object']=np.where(s.notna(),s.fillna(0).astype(int),df['Object'])
df
的输出:
Number Object
0 Name1 main
1 Name2 490348
2 Name3 237928
现在你可以检查df['Object']
的dtype:
df['Object'].map(type)
#output:
0 <class 'str'>
1 <class 'int'>
2 <class 'int'>
Name: Object, dtype: object
注意:拥有不同数据类型的列不是一个好主意
希望有人能帮助我 我有
数量 | 对象 |
---|---|
名字 1 | 主要 |
名字2 | 490348,0 |
名字3 | 237928,0 |
df 类型是“对象”列的对象 我需要摆脱浮点数并将它们变成整数。 但是我得到一个错误“无法将 float NaN 转换为整数”。
非常感谢!!!
您可以尝试通过 pd.to_numeric()
+np.where()
:
import numpy as np
s=pd.to_numeric(df['Object'].replace(',','',regex=True),errors='coerce')
df['Object']=np.where(s.notna(),s.fillna(0).astype(int),df['Object'])
df
的输出:
Number Object
0 Name1 main
1 Name2 490348
2 Name3 237928
现在你可以检查df['Object']
的dtype:
df['Object'].map(type)
#output:
0 <class 'str'>
1 <class 'int'>
2 <class 'int'>
Name: Object, dtype: object
注意:拥有不同数据类型的列不是一个好主意