Adding calculated column in Pandas

Viewed 111049

I have a dataframe with 10 columns. I want to add a new column 'age_bmi' which should be a calculated column multiplying 'age' * 'bmi'. age is an INT, bmi is a FLOAT.

That then creates the new dataframe with 11 columns.

Something I am doing isn't quite right. I think it's a syntax issue. Any ideas?

Thanks

df2['age_bmi'] = df(['age'] * ['bmi'])
print(df2)
4 Answers

You have combined age & bmi inside a bracket and treating df as a function rather than a dataframe. Here df should be used to call the columns as a property of DataFrame-

df2['age_bmi'] = df['age'] *df['bmi']

You can also use assign:

df2 = df.assign(age_bmi = df['age'] * df['bmi'])
Related