df.assign
specifically for this purpose. It returns a copy to avoid changing the original data frame and / or raising SettingWithCopyWarning
. It works as follows:
data_with_ave = ave_data.assign(average = ave_data.mean(axis=1, numeric_only=True))
This function can also create multiple columns at the same time:
data_with_ave = ave_data.assign( average = ave_data.mean(axis=1, numeric_only=True), median = ave_data.median(axis=1, numeric_only=True) )
Starting with panda 0.36, you can even refer to the newly created column to create another:
data_with_ave = ave_data.assign( average = ave_data.mean(axis=1, numeric_only=True), isLarge = lambda df: df['average'] > 10 )
source share