如何在 pandas 中交换值的两列分组? [英] How to group by two column with swapped values in pandas?

查看:48
本文介绍了如何在 pandas 中交换值的两列分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按交换规则适用的列分组.

I want to group by columns where the commutative rule applies.

例如column 1, column 2 在第一行包含值 (a,b)(b,a)对于另一行,那么我想将这两条记录分组执行分组操作.

For example column 1, column 2 contains values (a,b) in the first row and (b,a) for another row, then I want to group these two records perform a group by operation.

输入:

From    To  Count
a1      b1  4
b1      a1  3
a1      b2  2
b3      a1  12
a1      b3  6

<小时>

输出:

From    To  Count(+)
a1      b1  7
a1      b2  2
b3      a1  18

我尝试在交换元素后应用 group by.但是我没有任何方法可以解决这个问题.帮我解决这个问题.

I tried to apply group by after swapping the elements. But I don't have any approach to solve this problem. Help me to solve this problem.

提前致谢.

推荐答案

使用 numpy.sort 用于对每一行进行排序:

Use numpy.sort for sorting each row:

cols = ['From','To']
df[cols] = pd.DataFrame(np.sort(df[cols], axis=1))
print (df)
  From  To  Count
0   a1  b1      4
1   a1  b1      3
2   a1  b2      2
3   a1  b3     12
4   a1  b3      6

df1 = df.groupby(cols, as_index=False)['Count'].sum()
print (df1)
  From  To  Count
0   a1  b1      7
1   a1  b2      2
2   a1  b3     18

这篇关于如何在 pandas 中交换值的两列分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆