Sum the count of combination of two columns (in both directions) in Python Pandas

Viewed 261

I have the following dataframe.

>> df = pd.DataFrame.from_dict({'x':['A','C','E','B','F','D','A','D','C','B','D','C','E'], 
                                'y': ['B','D','F','A','D','F','C','F','E','D','B','A','C'], 
                                'count':[3,4,21,4,1,4,5,22,6,7,10,12,13]})
    x   y   count
0   A   B   3
1   C   D   4
2   E   F   21
3   B   A   4
4   F   D   1
5   D   F   4
6   A   C   5
7   D   F   22
8   C   E   6
9   B   D   7
10  D   B   10
11  C   A   12
12  E   C   13

I need to find the sum of count where if for example (x = 'A' and y = 'B') sums with (x = 'B' and y = 'A'). This shall be applied to all combinations.

So the output shall be something like this

   comb   sum
0  A-B    7
1  A-C    17
2  B-D    17
3  C-D    4
4  C-E    6
5  D-F    27
6  E-C    13
7  E-F    21
1 Answers

you can use np.sort to sort the columns then join the columns and groupby with sum:

s = pd.Series(map('-'.join , np.sort(df[['x','y']],axis=1)),name='comb')
out = df.groupby(s)['count'].sum().reset_index(name='Sum_of_Numbers')

print(out)

  comb  Sum_of_Numbers
0  A-B               7
1  A-C              17
2  B-D              17
3  C-D               4
4  C-E              19
5  D-F              27
6  E-F              21

Explanation:

First we sort columns x and y on axis=1 so we get the groups A,B and B,A as A,B , then we join them using -.join and the map function

print([*map('-'.join , np.sort(df[['x','y']],axis=1))])
#['A-B', 'C-D', 'E-F', 'A-B', 'D-F', 'D-F', 'A-C', 
 #'D-F', 'C-E', 'B-D', 'B-D', 'A-C', 'C-E']

Once we have this list we created a series of this list with name = comb so that we can use this as a helper column in df.groupby

Related