pandas 将邻接矩阵转换为边列表

xyhw6mcr  于 2023-02-27  发布在  其他
关注(0)|答案(3)|浏览(126)

如何将一个以PandasDataFrame表示的邻接矩阵转换为一个边列表?例如:

0  1  2  3  4
0  0  0  0  1  1
1  1  0  1  1  0
2  1  1  0  0  0
3  0  0  0  0  0
4  1  0  0  1  0

预期结果:

[(0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (4, 0), (4, 3)]

我的尝试:

import pandas as pd
import random
x = 5
table = []
row = []
for i in range(x):
  for j in range(x):
    if i == j :
      row.append(0)
    else :
      row.append(random.randint(0,1))
  table.append(row)
  row = []
df = pd.DataFrame(table)
df
ltqd579y

ltqd579y1#

IIUC,将0替换为NAstack(默认去掉NA),并将索引转换为列表:

df.replace(0, pd.NA).stack().index.to_list()

输出:

[(0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (4, 0), (4, 3)]

匹配输入:

0  1  2  3  4
0  0  0  0  1  1
1  1  0  1  1  0
2  1  1  0  0  0
3  0  0  0  0  0
4  1  0  0  1  0
0sgqnhkj

0sgqnhkj2#

df.apply(lambda ss:[(ss.name,i) for i in ss.loc[ss.eq(1)].tolist()],axis=1).explode().tolist()
eanckbw9

eanckbw93#

您可以使用numpy函数argwhere

np.argwhere(df.values == 1).tolist()

输出:

[[0, 3], [0, 4], [1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [4, 0], [4, 3]]

相关问题