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

时间:2017-09-27 05:44:58

标签: python pandas floating-point multiplication

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

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

但它给了我这个错误:

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

我该如何解决?

2 个答案:

答案 0 :(得分:1)

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

解决方案是通过astype转换为floatint

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

另一个问题是像gh这样的非数字数据,需要to_numeric转换errors='coerce'才能将它们转换为NaN s:

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

答案 1 :(得分:0)

也许这个答案太简单了,但这对我有用,而且相对简单。

Dataframe["new column"]  = (dataframe ["old column"] * by float constant)
January1st["weight_lb"] = (January1st["weight_kg"] * 2.2)

Dataframe.head() 看看它是否有效。