问题描述
0 1 4 5
1 0 2 6
2 1 3 7
3 2 4 8
4 0 3 9
5 0 7 8
6 1 8 9
7 2 5 9
8 3 5 6
9 4 6 7
其中第一行说 0 与 1、4 和 5 相邻;第二行是说 1 与 0、2 和 6 相邻;第三行是说 2 与 1、3 和 7 相邻,...
如何将其转换为这样的邻接矩阵?
0 1 0 0 1 1 0 0 0 0
1 0 1 0 0 0 1 0 0 0
0 1 0 1 0 0 0 1 0 0
0 0 1 0 1 0 0 0 1 0
1 0 0 1 0 0 0 0 0 1
1 0 0 0 0 0 0 1 1 0
0 1 0 0 0 0 0 0 1 1
0 0 1 0 0 1 0 0 0 1
0 0 0 1 0 1 1 0 0 0
0 0 0 0 1 0 1 1 0 0
解决方法
import numpy as np
adj_dict = {}
path_to_list = '../adj_list.txt'
# Replace with zero if vertices are connected to themselves
empty_digonal = 1
with open(path_to_list) as f:
adj_dict = {int(line.split()[0]):[int(x) for x in line.split()[empty_diagonal:]] for line in f.read().strip('\n').splitlines()}
adj_mx = np.zeros([len(adj_dict),len(adj_dict)])
for i in adj_dict:
adj_mx[i,adj_dict[i]] = 1
assert sum(sum(adj_mx - adj_mx.T)) == 0,'The matrix is not symmetric'
可能不是最佳解决方案,但它有效
,如何在数据帧内创建长度相同的定位 0 和 1 列表,然后将它们作为系列拉出。
# the lists will all be this length
maxlen = df.max().max()
df = pd.DataFrame([
[0,1,4,5],[1,2,6],[2,3,7],[3,8],[4,9],[5,7,[6,8,[7,5,[8,[9,6,7]])
# the function used to create the lists
def createlist(x):
arr=(maxlen+1)*[0]
arr[x]=1
return arr
# create the list for each cell,then concatenate the lists per row vertically,sum them,giving each final row
df2 = df.applymap(createlist).apply(lambda x: pd.concat([pd.Series(x[i]) for i in range(len(df.columns))],axis=1).sum(axis=1),axis=1)
df2
0 1 2 3 4 5 6 7 8 9
0 1 1 0 0 1 1 0 0 0 0
1 1 1 1 0 0 0 1 0 0 0
2 0 1 1 1 0 0 0 1 0 0
3 0 0 1 1 1 0 0 0 1 0
4 1 0 0 1 1 0 0 0 0 1
5 1 0 0 0 0 1 0 1 1 0
6 0 1 0 0 0 0 1 0 1 1
7 0 0 1 0 0 1 0 1 0 1
8 0 0 0 1 0 1 1 0 1 0
9 0 0 0 0 1 0 1 1 0 1
要将对角线设置为零,请执行以下操作:
df3 = df2.values
np.fill_diagonal(df3,0)
,
import numpy as np
rows = (
[0,7]
)
matrix = np.zeros((10,10))
for row in rows:
matrix[row[0],row[1:]] = 1
print(matrix)