Convert adjacency matrix to edge list

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

Upvotes: 2

Views: 295

Answers (2)

Mykola Zotko
Mykola Zotko

Reputation: 17814

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]]

Upvotes: 1

mozway
mozway

Reputation: 260490

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

Upvotes: 2

Related Questions