问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/46440291/how-do-i-multiply-a-dataframe-column-by-a-float-constant