pandas - 使用 Pandas 检查图互易性

标签 pandas graph

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

<表类=“s-表”> <标题> 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 中的源列和目标列后,您可以将 DataFrame 与其自身合并。然后对合并结果进行排序并删除重复项以获得唯一的相互节点对。

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

关于pandas - 使用 Pandas 检查图互易性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67991543/

相关文章:

pandas - pandas 中给定日期的周数

graph - Neo4J 节点与关系实体

algorithm - NP完全归约

ios:Coreplot,无法在一张图表上绘制多个图

python - 将 Python Pandas 数据框行与加法结合起来

python - pandas多索引数据框条件列串联

python pandas 用最大值填充 NaN 或毯子

python - 每个日期的点数总和按列表形式的附加列分组

python - Scipy 从文本文件构建网络图

php - 特殊图中的最重路径(PHP)