简体   繁体   中英

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

data is given like this in a text file:

AB 1
B C -1
A C 1
BD 1
DA -1
C D 1

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM