【问题标题】:Find the mean of columns with matching column names查找具有匹配列名的列的平均值
【发布时间】:2020-10-16 09:01:51
【问题描述】:

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

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,因此不能按索引位置分组。

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

【问题讨论】:

  • 您的数据中有name, x, y 普通列吗?另外你的预期输出是什么?
  • name, x, y 是列,但我不想对它们执行任何操作。我希望平均文件的输出如下所示:我会将所需的输出添加到问题中,因为它在评论中的格式不正确并删除第一列,因为它们不相关,我可以轻松合并这些列使用我创建的临时 df。

标签: python pandas group-by average mean


【解决方案1】:

您可以将df.columns 转换为设置然后迭代:

df = pd.DataFrame([[1, 2, 3, 4, 5, 6]], columns=['a', 'a', 'a', 'b', 'b', 'b'])

for column in set(df.columns):
    print(column, df[common_name].mean(axis=1))

将输出

a 0    2.0
dtype: float64
b 0    5.0
dtype: float64

如果订单很重要,请使用sorted

for column in sorted(set(df.columns)):

从这里你可以得到几乎任何你想要的格式的输出。

【讨论】:

    【解决方案2】:

    一个选项是分组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
    

    【讨论】:

    • 问题比我想象的要复杂一些,因为整个列名不是完全匹配的。我相应地编辑了帖子,并列出了当我认为每列只有 3 个代表时我使用的内容。有没有类似于这种方法的解决方案可行?
    • 谢谢!你能解释一下d = df.filter在做什么吗?
    • 提取所有包含gh的列。修改该行,根据您的内心内容进行评论。
    • 太棒了。下面使用 iloc 的行也在做同样的事情,但使用索引而不是名称?
    • 是的,通过列的数字索引而不是名称。
    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 2018-07-12
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多