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

天涯浪子 提交于 2019-12-02 05:05:09

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

Solution is converting to float, int by 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_numeric with errors='coerce' for converting them to 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!