Krishna Nevase
Krishna Nevase

Reputation: 105

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)/3540)

But it gives me this error:

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

How do I solve it?

Upvotes: 1

Views: 17730

Answers (2)

Maybe this is too simple an answer, but this worked for me and is relatively simple.

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

Dataframe.head() to see whether it worked.

Upvotes: 0

jezrael
jezrael

Reputation: 862751

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

Upvotes: 2

Related Questions