将列添加到Pandas DataFrame的末尾,其中包含先前数据的平均值 [英] Add column to the end of Pandas DataFrame containing average of previous data

查看:304
本文介绍了将列添加到Pandas DataFrame的末尾,其中包含先前数据的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame ave_data ,其中包含以下内容:

I have a DataFrame ave_data that contains the following:

ave_data

Time        F7           F8            F9  
00:00:00    43.005593    -56.509746    25.271271  
01:00:00    55.114918    -59.173852    31.849262  
02:00:00    63.990762    -64.699492    52.426017

我想在此数据框中添加另一列,其中包含F7列下的平均值,每行F8和F9。

I want to add another column to this dataframe, containing the average of the values under column F7, F8 and F9 for each row.

ave_data DataFrame可能会更改大小,因为以后我的代码从不同的Excel文件读取,因此该方法需要通用的(即,将包含平均值的列始终作为DataFrame的最后一列,而不是列号4)

The ave_data DataFrame might change size as my code reads from different Excel files later, so the method needs to be generic (i.e add the column containing the average always as the last column in the DataFrame, not in column number 4)

desired output

Time        F7           F8            F9           Average
00:00:00    43.005593    -56.509746    25.271271    4.25  
01:00:00    55.114918    -59.173852    31.849262    9.26
02:00:00    63.990762    -64.699492    52.426017    17.24


推荐答案

您可以复制您的df使用 copy()然后调用 mean 并传递参数 axis = 1 numeric_only = True ,以便按行计算平均值,并忽略非数字列,当您执行以下操作时,将始终添加该列最后:

You can take a copy of your df using copy() and then just call mean and pass params axis=1 and numeric_only=True so that the mean is calculated row-wise and to ignore non-numeric columns, when you do the following the column is always added at the end:

In [68]:

summary_ave_data = df.copy()
summary_ave_data['average'] = summary_ave_data.mean(numeric_only=True, axis=1)
summary_ave_data
Out[68]:
                 Time         F7         F8         F9    average
0 2015-07-29 00:00:00  43.005593 -56.509746  25.271271   3.922373
1 2015-07-29 01:00:00  55.114918 -59.173852  31.849262   9.263443
2 2015-07-29 02:00:00  63.990762 -64.699492  52.426017  17.239096

这篇关于将列添加到Pandas DataFrame的末尾,其中包含先前数据的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆