从旧数据帧创建新数据帧,其中新数据帧包含旧数据帧中不同位置的列的行平均值



我有一个名为"框架";具有16列和201行。附上了一张截图,提供了一个示例数据帧

在此处输入图像描述

请注意,屏幕截图只是一个例子,原始数据帧要大得多。

我想找到一种有效的方法(可能使用for循环或编写函数(来逐行平均数据帧中的不同列。例如,为了找到列"strong"的平均值;rep";以及";rep1"和列"strong>";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']

上面的代码完成了这项工作,但注意每一列的位置是很乏味的。我更希望自动化这个过程,因为其他数据文件也会重复这个过程。

基于你的愿望"我宁愿自动化这个过程,因为这对其他数据文件也是重复的;我能想到的是下面这个:

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

最新更新