pandas 将数据框列转换为浮动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38133785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:29:58  来源:igfitidea点击:

Converting a dataframe column to float

pythonpandas

提问by Stacey

I have a dataframes called historic_pricewith two columns called 'price'and 'item'that I am trying to multiple together storing the result in a different data-frame called dayData, but I get the exception:

我有一个数据帧,historic_price其中有两列被调用'price''item'并且我试图将结果多个存储在一个名为 的不同数据帧中dayData,但我得到了异常:

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

The 'price'column looks like:

'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

The 'item'column looks like:

'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

(I know all of the values are zero but even so when I multiple price by item I shoud still get a result (0))

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

the data types for the two columns are both <class 'pandas.core.series.Series'>

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

I am trying to add the product of item and price to the dayDatadataframe as follows:

我正在尝试将商品和价格的产品添加到dayData数据框中,如下所示:

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

but I get the exception above.

但我得到了上面的例外。

I have tried converting the columns to float:

我曾尝试将列转换为浮动:

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

but with no luck (I get the exception: TypeError: cannot convert the series to <class 'float'>)

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

Can anyone let me know what i need to do to fix please?

任何人都可以让我知道我需要做什么来修复吗?

Many thanks

非常感谢

回答by Kamil Sindi

It's highly likely you have strings in one of the columns. Try using to_numeric with errors set to 'coerce':

您很可能在其中一列中有字符串。尝试使用 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']