Home > front end >  How to make an N by N matrix using python in which value for each a(i,j) is known?
How to make an N by N matrix using python in which value for each a(i,j) is known?

Time:06-19

data is given like this in a text file:

A B 1
B C -1
A C 1
B D 1
D A -1
C D 1

and the matrix has to be like:
\ A B C D
A 0 1 1 -1
B 1 0 -1 1
C 1 -1 0 1
D -1 1 1 0

CodePudding user response:

In your case

#df = pd.read_csv('your file.txt')

s = df.pivot(*df.columns)
out = s.T.add(s,fill_value=0).fillna(0)
Out[745]: 
col1    A    B    C    D
col2                    
A     0.0  1.0  1.0 -1.0
B     1.0  0.0 -1.0  1.0
C     1.0 -1.0  0.0  1.0
D    -1.0  1.0  1.0  0.0

CodePudding user response:

Can also pivot_table and make the final df symmetric by summing with the transpose:

arr = (df.pivot_table(index='col1', 
                      columns='col2',
                      values='val')
         .fillna(0))

arr = arr.T
  • Related