查找连续列的平均值

Finding the mean of consecutive columns

我有一个非常大的数据文件(数万行和列),其格式与此类似。

name   x  y gh_00hr_bio_rep1 gh_00hr_bio_rep2 gh_00hr_bio_rep3 gh_06hr_bio_rep1
gene1  x  y         2               3               2               1
gene2  x  y         5               7               6               2

我对每个基因的目标是找到每组重复的平均值。

最后,我希望只有平均值列的标题类似于“00hr_bio”,并删除所有单独的重复项。

我现在的想法是使用这样的东西:

for row in df:
    df[avg] = df.iloc[3:].rolling(window=3, axis=1).mean() 

但我不知道如何实际进行这项工作。

df.iloc[3] 是我尝试从第 3 列开始的方式,但我相当确定这样做是行不通的。

我什至不知道从哪里开始将 3 列“合并”为 1 列。

非常感谢您的任何建议,因为我显然不知道自己在做什么。

你很接近。

df['avg'] = df.iloc[:, 2:].mean(axis=1)

会给你这个:

       x  y  gh_00hr_bio_rep1  gh_00hr_bio_rep2  gh_00hr_bio_rep3  gh_06hr_bio_rep1  avg
gene1  x  y                 2                 3                 2                 1  2.0
gene2  x  y                 5                 7                 6                 2  5.0

如果您想从不同的列集合中获取平均值,您可以这样做:

for col in range(10):
    df['avg%i' % col] = df.iloc[:, 2+col*5:7+col*5].mean(axis=1)

如果每个平均值的列数相同。否则,您可能希望使用代表列的名称,具体取决于您的数据。

我会首先构建一系列由原始列索引的最终名称:

names = pd.Series(['_'.join(i.split('_')[:-1]) for i in df.columns[3:]],
                  index = df.columns[3:])

然后我会用它来询问轴 1 上的 groupby 的平均值:

tmp = df.iloc[:, 3:].groupby(names, axis=1).agg('mean')

它提供了一个新的数据框,其索引与原始数据框类似,并具有平均列:

   gh_00hr_bio  gh_06hr_bio
0     2.333333          1.0
1     6.000000          2.0

然后您可以将其水平连接到第一个数据框或其前 3 列:

result = pd.concat([df.iloc[:, :3], tmp], axis=1)

获得:

    name  x  y  gh_00hr_bio  gh_06hr_bio
0  gene1  x  y     2.333333          1.0
1  gene2  x  y     6.000000          2.0