[英]how can i sum all values depend on index value in pandas?
One way using frozenset
:使用
frozenset
一种方法:
df = df.reset_index()
df['total'].groupby(df[['type1', 'type2']].apply(frozenset, 1)).sum()
Output:输出:
(b, a) 15
(c, a) 19
Name: total, dtype: int64
Let df
be your DataFrame.让
df
成为您的 DataFrame。 Swap the first and second levels of the MultiIndex, concatenate the original and the new DataFrames, and calculate row sums:交换MultiIndex的第一层和第二层,连接原始数据帧和新数据帧,并计算行总和:
pd.concat([df, df.swaplevel()], axis=1).sum(1)
#a b 15
# c 19
#b a 15
#c a 19
The solution works even for the rows that do not have matching reversed rows.该解决方案甚至适用于没有匹配反向行的行。 The answer has duplicated rows for the direct and the reversed index.
答案对直接和反向索引有重复的行。 You will have to filter out the unwanted rows.
您必须过滤掉不需要的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.