我有以下数据框:
df2 = pd.DataFrame({'price': [Decimal(1.4334), Decimal(1.4335), Decimal(1.4336), Decimal(1.4337)], 'tpo_count': [1, 2, 3, 1], 'tpo': ['A', 'BC', 'BCD', 'D']})
print(df2.dtypes)
price object
tpo_count int64
tpo object
dtype: object
如果想要创建一个名为“price_float”的附加列,该列与“price”相同,但带有 float (稍后使用不支持十进制的 matplotlib 进行绘制)。
我已经尝试过:
df2['price_float']=float(df2['price'])
但我得到:
TypeError: cannot convert the series to <class 'float'>
最佳答案
只是模拟您的示例 DataFrame:
示例 DataFarme:
>>> df2
price tpo tpo_count
0 1.4334 A 1
1 1.4335 BC 2
2 1.4336 BCD 3
3 1.4337 D 1
>>> print(df2.dtypes)
price object
tpo object
tpo_count int64
dtype: object
解决方案..
>>> df2['price_float'] = df2['price'].astype(float)
>>> df2
price tpo tpo_count price_float
0 1.4334 A 1 1.4334
1 1.4335 BC 2 1.4335
2 1.4336 BCD 3 1.4336
3 1.4337 D 1 1.4337
现在您已经创建了新的float
列..
>>> print(df2.dtypes)
price object
tpo object
tpo_count int64
price_float float64
dtype: object
关于python - 将 pandas 中的 Decimal 列转换为 float 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57450475/