pandas 如何将数据帧列乘以浮点常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46440291/
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 04:32:04  来源:igfitidea点击:

How do I multiply a dataframe column by a float constant?

pythonpandasfloating-pointmultiplication

提问by Krishna Nevase

I'm trying to multiply a column by a float. I have the code for it here:

我正在尝试将一列乘以一个浮点数。我在这里有它的代码:

if str(cMachineName)==str("K42"):
        df_temp.loc[:, "P"] *= float((105.0* 59.0*math.pi*0.95/1000)/3540)

But it gives me this error:

但它给了我这个错误:

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

How do I solve it?

我该如何解决?

回答by jezrael

I think problem is some non numeric values like 45as string:

我认为问题是一些非数字值,如45字符串:

Solution is converting to float, intby astype:

解决方案正在转换为floatint通过astype

df_temp = pd.DataFrame({'P':[1,2.5,'45']})

print (df_temp['P'].dtype)
object

df_temp["P"] = df_temp["P"].astype(float)
df_temp["P"] *= float((105.0* 59.0*math.pi*0.95/1000)/3540)
print (df_temp)
          P
0  0.005223
1  0.013057
2  0.235030

Another problem is non numeric data like gh, for converting is necessary to_numericwith errors='coerce'for converting them to NaNs:

另一个问题是非数字数据,如gh,转换是必要的to_numericerrors='coerce'以便将它们转换为NaNs:

df_temp = pd.DataFrame({'P':[1,2.5,'gh']})

print (df_temp['P'].dtype)
object

df_temp["P"] = pd.to_numeric(df_temp["P"], errors='coerce')
print (df_temp)
     P
0  1.0
1  2.5
2  NaN

df_temp["P"] *= float((105.0* 59.0*math.pi*0.95/1000)/3540)
print (df_temp)

          P
0  0.005223
1  0.013057
2       NaN