gpt4 book ai didi

python - 将数据框列转换为 float

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:08 25 4
gpt4 key购买 nike

我有一个名为 historic_price 的数据框有两列称为 'price''item'我正在尝试将结果多重存储在一个名为 dayData 的不同数据框中,但我得到了异常(exception):

TypeError: can't multiply sequence by non-int of type 'float'

'price'列看起来像:

           price
0 5.86500
1 2.03000
2 13.55000
3 639.75450
4 343.94325
5 1009.43500
6 585.60600
7 2208.72400
8 807.54800
9 236.51530
10 14.34000

'item'列看起来像:

     item
0 0.0
1 0.0
2 0.0
3 0.0
4 0.0
5 0.0
6 0.0
7 0.0
8 0.0
9 0.0
10 0.0

(我知道所有的值都是零,但即便如此,当我按项目乘以价格时,我仍然会得到结果(0))

两列的数据类型都是<class 'pandas.core.series.Series'>

我正在尝试将商品和价格的乘积添加到 dayData数据框如下:

dayData["cash"]  =  historicPrice["price"]  * historicPrice["item"]

但我得到了上面的异常。

我试过将列转换为 float :

dayData["cash"]  =  float(historicPrice["price"])  * float(historicPrice["item"])

但没有运气(我得到异常(exception):TypeError: cannot convert the series to <class 'float'>)

谁能告诉我我需要做些什么来解决这个问题?

非常感谢

最佳答案

您很可能在其中一列中有字符串。尝试使用 to_numeric 并将错误设置为“强制”:

df['price'] = pd.to_numeric(df['price'], errors='coerce').fillna(0)
df['item'] = pd.to_numeric(df['item'], errors='coerce').fillna(0)

df['cash'] = df['price'] * df['item']

关于python - 将数据框列转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com