python - 将数据框列转换为 float

标签 python pandas

我有一个名为 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/

相关文章:

python - 将数据分组并汇总到新的 pandas 数据框中

python - 使用 Unicode 字符打印 Pandas 列

python - Pandas 迭代行并将 API 响应附加为新列

python - 计算特定行的平均值

python - 如何根据条件将字符串数组转换为结构体数组

python - 当我尝试使用 pip install psycopg2 安装 psycopg2 时出现此错误。我应该怎么办?

python - Pandas 系列拆分 n 次

python - 从字典中向 pandas 数据框添加新列

Python IPv6 字节地址

javascript - 如何将 float 的 numpy 数组序列化为字符串?