数据列的值不会改变浮动
问题描述:
我有一个数据帧,数据列的值不会改变浮动
df,
Name Stage Description
0 sri 1 sri is one of the good singer in this two
1 nan 2 thanks for reading
2 ram 1 ram is two of the good cricket player
3 ganesh 1 one driver
4 nan 2 good buddies
tried df["Stage"]=pd.to_numeric(df["Stage"],downcast="float")
但仍值是相同
答
您可以使用df.Stage.astype(float)
:
In [6]: df.Stage.astype(float)
Out[6]:
0 1.0
1 2.0
2 1.0
3 1.0
4 2.0
Name: Stage, dtype: float64
In [7]: df.Stage.astype(float)
使用pd.to_numeric
更好,因为它处理转换为占用较少内存的浮点类型。
例
In [23]: df.Stage
Out[23]:
0 1
1 2
2 1
3 1
4 2
Name: Stage, dtype: int64
In [24]: import sys
In [25]: sys.getsizeof(df.Stage)
Out[25]: 272
In [26]: sys.getsizeof(df.Stage.astype(float))
Out[26]: 272
In [27]: sys.getsizeof(pd.to_numeric(df.Stage, downcast='float'))
Out[27]: 252
的情况下有在df.Stage坏数据,胁迫价值NaN
pd.to_numeric(df.Stage, errors='coerce', downcast='float')
答
我想你需要astype
:
df["Stage"]=df["Stage"].astype(float)
如果第一解决方案失败,因为一些非数字数据,使用to_numeric
wi用于更换损坏的数据NaNs
个参数errors='coerce'
,所以输出是浮动:
df["Stage"]=pd.to_numeric(df["Stage"],errors="coerce")
我想你需要'DF [ “舞台”] = pd.to_numeric(DF [ “舞台”],错误= “要挟”) ' – jezrael
我想要浮点数 – pyd
尝试过df [“Stage”] = pd.to_numeric(df [“Stage”],errors =“coerce”)但仍然一样 – pyd