How to make graph from table Python?

Viewed 51

if i have code like this

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

and the output will be there Output

how to make graph from this table ? i want the output graph like this [(0,1), (0,2), (1,0), (1,2), (1,4), (2,3), (2,4), (3,0), (3,1), (3,2), (3,4), (4,0)]

1 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
Related