简体   繁体   English

我如何总结所有值取决于熊猫中的索引值?

[英]how can i sum all values depend on index value in pandas?

I want to calculate some values between type1 and type2 elements.我想计算 type1 和 type2 元素之间的一些值。 For example if have index like: (a,b) and (b,a) then it will equals to (a,b)+(b,a) I want to sum values if reverse indexes exists.例如,如果有如下索引: (a,b)(b,a)那么它将等于(a,b)+(b,a)如果存在反向索引(a,b)+(b,a)我想对值求和。

表格截图

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.

相关问题 我如何总结字典中具有相同索引的所有值,其中每个键都有一个嵌套列表作为值? - How can i sum up all values with the same index in a dictionary which each key has a nested list as a value? 如何基于索引将来自不同字典的值加到pandas现有列中? - How can i sum values to a pandas existing column from different dictionaries based on index? 如何在多索引数据透视表中汇总Pandas Dataframe值是否存在? - How can I sum Pandas Dataframe values in multi-index pivot whether they exist or not? Python Pandas:如何在 dataframe 的列中对字典的所有值求和? - Python Pandas: How can I sum all of the values of a dictionary in a column of my dataframe? 如何使用python将所有索引值的总和加到numpy ndarray的每个元素中? - How can I add to each element of a numpy ndarray the sum of all its index values with python ? 如何对与pandas DataFrame中另一列的特定值对应的列值求和? - How can I sum column values that corrispond to a specific value of another column in a pandas DataFrame? 如何根据熊猫中另一列的底值将一列中的值求和? - How can I sum the values in one column based on the floor'd value of another column in pandas? 如何编写 Python 代码来查找特定行值的 Pandas DF 中列的值的总和? - How can I write the Python code to find the sum of values of a column in a Pandas DF for a specific row value? Pandas 按索引求和值 - Pandas SUM value by Index 使用numpy,如何生成一个数组,其中每个索引的值是从0到第二个数组中相同索引的值的总和? - Using numpy, how can I generate an array where the value at each index is the sum of the values from 0 to that same index in a second array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM