How Do I Multiply A Dataframe Column By A Float Constant?
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)/354
Solution 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
00.00522310.01305720.235030
Another problem is non numeric data like gh
, for converting is necessary to_numeric
with errors='coerce'
for converting them to 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
01.012.52 NaN
df_temp["P"] *= float((105.0* 59.0*math.pi*0.95/1000)/3540)
print (df_temp)
P
00.00522310.0130572 NaN
Solution 2:
Maybe this is too simple an answer, but this worked for me and is relatively simple.
Dataframe["new column"] = (dataframe ["old column"] * byfloat constant)
January1st["weight_lb"] = (January1st["weight_kg"] * 2.2)
Dataframe.head()
to see whether it worked.
Post a Comment for "How Do I Multiply A Dataframe Column By A Float Constant?"