我有一个名为“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']
上面的代码完成了这项工作,但要注意每一列的位置是很乏味的。我更愿意自动执行此过程,因为其他数据文件也会重复此过程。
答案 0 :(得分:0)
基于您的愿望“我宁愿自动化此过程,因为其他数据文件也会重复此过程” 我能想到的是下面这个:
in [1]: frame = pd.read_csv('your path')
结果如下所示,现在你可以看到你想要平均的是第 1,5 和 2,6 列等等。
out [1]:
sample rep repcycle set setcycle rep1 repcycle1 set1 setcycle1
0 66 40 4 5 3 40 4 5 3
1 78 20 5 6 3 20 5 6 3
2 90 50 6 9 4 50 6 9 4
3 45 70 7 3 2 70 7 7 2
所以,我们需要创建 2 个列表
in [2]: import numpy as np
list_1 = np.arange(1,5,1).tolist()
in [3]: list_1
out[3]: [1,2,3,4]
这对于你想要平均的上半年[rep,repcycle,set,setcycle]
in [4]: list_2 = [x+4 for x in list_1]
in [5]: list_2
out[5]: [5,6,7,8]
这对于你想要平均的下半场[rep1,repcycle1,set1,setcycle1]
in [6]: result = pd.concat([frame.iloc[:, [x,y].mean(axis=1) for x, y in zip(list_1,list_2)],axis=1)
in [7]: result.columns = ['Re', 'Rec', 'Se', 'Sec']
现在你得到了你想要的东西,而且它是自动化的,你需要做的就是改变上面的两个列表。
in [8]: result
out[8]:
Re Rec Se Sec
0 40.0 4.0 5.0 3.0
1 20.0 5.0 6.0 3.0
2 50.0 6.0 9.0 4.0
3 70.0 7.0 5.0 2.0