下面我有一个数据样本:
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.我想不出如何在循环中追加新的总计列来生成我的最终结果。
任何帮助都将受到感谢(或更好的建议,作为反对循环)。谢谢。
发布于 2020-11-18 23:56:01
您可以使用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发布于 2020-11-18 23:57:46
让我们试试看,split,然后groupby和axis=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发布于 2020-11-21 09:05:53
另一个选项是,我们创建一个按列分组的字典:
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 3https://stackoverflow.com/questions/64903216
复制相似问题