我有很多邻接矩阵,我已经使用下面的内容将它们转换为边列表(存储为列表)(我愿意接受更好的边列表代码,尽管这不是本文的重点):
def edges (mat):
edgelist = []
n = len(mat)
for i in range(n):
for j in range(n):
if i<j:
if mat[i][j] > 0.0001:
edgelist.append([abs(float(mat[i][j])),i,j])
edgeframe = pandas.DataFrame(edgelist)
return edgeframe
我想评估
edge_lists[0]
和 edge_lists[4]
之间的边缘差异。
具体来说,我想知道哪些条目从第一个边缘列表到下一个边缘列表消失了。我的第一个想法是看看有多少行和列使用这个保持不变:
adj1 = edge_lists[0]
adj2 = edge_lists[4]
np.sum(adj1 == adj2)
0 0
1 56
2 39
dtype: int64
但这不起作用。第一个邻接矩阵可以在第 5 行、第 5 列中具有非零值。该条目可以是第一个边列表的第 20 行。如果第二个邻接矩阵的第 5 行第 5 列也有非零值,但该条目是第二个边列表的第 21 行,则上述代码将崩溃。
有没有办法为边缘列表分配唯一值来表示行和列的精确组合?在 Excel 中,我将为每个边缘列表创建“行和列”并比较两者。我不知道如何在 python 中做到这一点。
import pandas as pd
def assign_edge_labels(edgeframe):
edgeframe['edge_label'] = edgeframe.apply(lambda row: f"{row[1]}&{row[2]}", axis=1)
return edgeframe
# Create edge lists
edge_lists = [edges(mat1), edges(mat2)] # Replace mat1 and mat2 with your adjacency matrices
# Assign unique labels to each edge in the edge lists
edge_lists[0] = assign_edge_labels(edge_lists[0])
edge_lists[1] = assign_edge_labels(edge_lists[1])
# Find the edges that disappeared from the first edge list to the second edge list
disappeared_edges = edge_lists[0][~edge_lists[0]['edge_label'].isin(edge_lists[1]['edge_label'])]
print(disappeared_edges)