求和后向 DF 追加新列?

Append new column to DF after sum?

下面有一个示例数据框:

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.

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

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

您可以使用 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

让我们试试,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

另一种选择,我们创建一个字典以按列分组:

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