Add column to the end of Pandas DataFrame containing average of previous data

前端 未结 4 1275
深忆病人
深忆病人 2021-02-12 14:04

I have a DataFrame ave_data that contains the following:

ave_data

Time        F7           F8            F9  
00:00:00    43.005593    -56.509746           


        
4条回答
  •  孤城傲影
    2021-02-12 14:36

    df.assign is specifically for this purpose. It returns a copy to avoid changing the original dataframe 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)
    )
    

    As of pandas 0.36, you can even reference a column just created to create another:

    data_with_ave = ave_data.assign(
                        average = ave_data.mean(axis=1, numeric_only=True),
                        isLarge = lambda df: df['average'] > 10
    )
    

提交回复
热议问题