我在 pandas 中加载了一个图表,我想检查我的图表是否具有互易性的节点。我的数据集如下所示:
我的代码所需的输出是互逆节点:(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/