How To Group By Two Column With Swapped Values In Pandas?
I want to group by columns where the commutative rule applies. For example column 1, column 2 contains values (a,b) in the first row and (b,a) for another row, then I want to grou
Solution 1:
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
Post a Comment for "How To Group By Two Column With Swapped Values In Pandas?"