Convert adjacency matrix to edge list

Question:

How can I convert an adjacency matrix as pandas DataFrame to an edge list? For example:

   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

Desired result:

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

My attempt:

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

Answers:

IIUC, replace 0 by NA, stack (which drops the NA by default), and convert the index to list:

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

output:

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

matching input:

   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
Answered By: mozway
df.apply(lambda ss:[(ss.name,i) for i in ss.loc[ss.eq(1)].tolist()],axis=1).explode().tolist()
Answered By: G.G

You can use the numpy function argwhere:

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

Output:

[[0, 3], [0, 4], [1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [4, 0], [4, 3]]
Answered By: Mykola Zotko
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.