Check Graph Reciprocity using Pandas

Viewed 27

I have a Graph loaded in pandas and I want to check if my graph has nodes with reciprocity. My dataset looks like this:

id from to
0 s01 s03
1 s02 s01
2 s03 s01

The desired output of my code is the reciprocal nodes: (s01, s03)

I found a solution transforming my dataframe into tuples and comparing each combination of my nodes, but I'm sure this solution is far from ideal. Following is my code:

import pandas as pd
    
    t1 = list(zip(input_table_1['from'], input_table_1['to']))
    t2 = list(zip(input_table_1['to'], input_table_1['from']))
    
    r = [] #reciprocity nodes
    for tuple_1 in t1:
        for tuple_2 in t2:
            if tuple_2 == tuple_1 and (tuple_2 not in r and tuple_2[::-1] not in r):
                r.append(tuple_2)
    
    output_table_1 = pd.DataFrame(r, columns=['from', 'to'])

Is there a way to do that checking only using pandas structure?

Thanks in advance!

1 Answers

You can merge the DataFrame with itself after swapping the from and to columns in the right DataFrame. Then sort the merged result and drop duplicates to get the unique pairs of reciprocal nodes.

res = df[['from', 'to']].merge(df[['from', 'to']].rename(columns={'from': 'to', 'to': 'from'}))

pd.DataFrame(np.sort(res.to_numpy()), columns=['node1', 'node2']).drop_duplicates()
#  node1 node2
#0   s01   s03
Related