首页 > 解决方案 > 查找具有匹配列名的列的平均值

问题描述

我有一个类似于以下但有数千行和列的数据框:

x  y  ghb_00hr_rep1  ghb_00hr_rep2    ghb_00hr_rep3   ghl_06hr_rep1  ghl_06hr_rep2
x  y           2           3                 2                1         3
x  y           5           7                 6                2         1

我希望我的输出看起来像这样:

 ghb_00hr     hl_06hr
    2.3           2
     6           1.5

我的目标是找到匹配列的平均值。我想出了这个:temp = df.groupby(name, axis=1).agg('mean')但我不确定如何将“名称”定义为匹配列。

我之前的策略如下:

name = pd.Series(['_'.join(i.split('_')[:-1]) 
        for i in df.columns[3:]],
        index = df.columns[3:]
)
temp = df.groupby(name, axis=1).agg('mean')
    avg = pd.concat([df.iloc[:, :3], temp], 
    axis=1
)

但是,“复制”的数量范围为 1-4,因此按索引位置分组不是一种选择。

不确定是否有更好的方法可以做到这一点,或者我是否走在正确的轨道上。

标签: pythonpandasgroup-byaveragemean

解决方案


一个选项是 groupby level=0

(df.set_index(['name','x','y'])
   .groupby(level=0, axis=1)
   .mean().reset_index()
)

输出:

    name  x  y  ghb_00hr  ghl_06hr
0  gene1  x  y  2.333333       2.0
1  gene2  x  y  6.000000       1.5

更新:对于修改后的问题:

d = df.filter(like='gh')
# or d = df.iloc[:, 2:]
# depending on your columns of interest

names = d.columns.str.rsplit('_', n=1).str[0]

d.groupby(names, axis=1).mean()

输出:

   ghb_00hr  ghl_06hr
0  2.333333       2.0
1  6.000000       1.5

推荐阅读