【问题标题】:Append new column to DF after sum?求和后将新列附加到 DF?
【发布时间】:2021-03-02 07:40:09
【问题描述】:

我在下面有一个示例数据框:

sn C1-1 C1-2 C1-3 H2-1 H2-2 K3-1 K3-2
1   4     3    5    4    1    4    2
2   2     2    0    2    0    1    2
3   1     2    0    0    2    1    2

我想根据 C1、H2、K3 的前缀求和,并输出三个新列的总和。最后的结果是这样的:

sn total_c1 total_h2 total_k3
1      12      5        6
2      4       2        3
3      3       2        3

我对原始 df 的尝试:

lst = ["C1", "H2", "K3"]
lst2 = ["total_c1", "total_h2", "total_k3"]

for k in lst:
    idx = df.columns.str.startswith(i)
    for j in lst2:
        df[j] = df.iloc[:,idx].sum(axis=1)
        df1 = df.append(df, sort=False)

但我一直收到错误

IndexError: Item wrong length 35 instead of 36.

我不知道如何附加新的总计列以在循环中生成我的最终结果。

任何帮助将不胜感激(或更好的建议,而不是循环)。谢谢。

【问题讨论】:

    标签: pandas dataframe for-loop append


    【解决方案1】:

    你可以使用groupby:

    # columns of interest
    cols = df.columns[1:]
    
    col_groups = cols.str.split('-').str[0]
    out_df = df[['sn']].join(df[cols].groupby(col_groups, axis=1)
                                .sum()
                                .add_prefix('total_')
                            )
    

    输出:

       sn  total_C1  total_H2  total_K3
    0   1        12         5         6
    1   2         4         2         3
    2   3         3         2         3
    

    【讨论】:

      【解决方案2】:

      让我们试试split 然后groupbyaxis=1 一起使用

      out = df.groupby(df.columns.str.split('-').str[0],axis=1).sum().set_index('sn').add_prefix('Total_').reset_index()
      Out[84]: 
         sn  Total_C1  Total_H2  Total_K3
      0   1        12         5         6
      1   2         4         2         3
      2   3         3         2         3
      

      【讨论】:

        【解决方案3】:

        另一个选项,我们创建一个字典来按列分组:

        mapping = {entry: f"total_{entry[:2]}" for entry in df.columns[1:]}
        result = df.groupby(mapping, axis=1).sum()
        result.insert(0, "sn", df.sn)
        result
        
           sn   total_C1    total_H2    total_K3
        0   1      12          5          6
        1   2      4           2          3
        2   3      3           2          3
        

        【讨论】:

          猜你喜欢
          • 2016-10-25
          • 1970-01-01
          • 1970-01-01
          • 2018-09-23
          • 2021-11-07
          • 2021-10-31
          • 2021-02-23
          • 1970-01-01
          • 2021-04-26
          相关资源
          最近更新 更多