我有一个名为“frame”的数据框架,有16列201行。附加了一个屏幕截图,提供了一个示例数据帧
请注意,屏幕截图只是一个示例,原始数据帧要大得多
我想找到一种有效的方法(可能使用for循环或编写函数)对数据帧中的不同列进行行平均。例如,要查找列“rep”和“rep1”的平均值,以及列“repcycle”和“repcycle1”(类似于set和setcycle)的平均值,并将其保存在仅包含平均列的新数据框中
我尝试过使用iloc编写代码
newdf= frame[['sample']].copy()
newdf['rep_avg']=frame.iloc[:, [1,5]].mean(axis=1) #average row-wise
newdf['repcycle_avg']=frame.iloc[:, [2,6]].mean(axis=1)
newdf['set_avg']=frame.iloc[:, [3,7]].mean(axis=1) #average row-wise
newdf['setcycle_avg']=frame.iloc[:, [4,8]].mean(axis=1)
newdf.columns = ['S', 'Re', 'Rec', 'Se', 'Sec']
上面的代码完成了这项工作,但是记下每一列的位置是很乏味的。我更愿意将此过程自动化,因为其他数据文件也会重复此过程
根据您的要求,“我更愿意自动化此过程,因为其他数据文件也会重复此过程” 我能想到的是:
结果如下所示,现在您可以看到要求平均值的是第1、5和2、6列,依此类推
因此,我们需要创建两个列表
这是您希望平均[rep,repcycle,set,setcycle]的前半部分
这是您想要平均的下半部分[rep1,repcycle1,set1,setcycle1]
现在你得到了你想要的,而且它是自动化的,你所需要做的就是改变上面的两个列表
相关问题 更多 >
编程相关推荐