使用 Pandas 检查图形互易性

Check Graph Reciprocity using Pandas

我在 pandas 中加载了一个图,我想检查我的图是否有具有互惠性的节点。我的数据集如下所示:

id 来自
0 s01 s03
1 s02 s01
2 s03 s01

我的代码的期望输出是倒数节点:(s01, s03)

我找到了一个将我的数据框转换为元组并比较我的节点的每个组合的解决方案,但我确信这个解决方案远非理想。以下是我的代码:

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'])

有没有办法只使用 pandas 结构进行检查?

提前致谢!

您可以在交换右侧 DataFrame 中的 from 和 to 列后将 DataFrame 与自身合并。然后 sort 合并结果并删除重复项以获得唯一的互惠节点对。

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