Pandas extract columns and rows by ID from a distance matrix

Viewed 156

I have a distance matrix with IDs as column and row names:

    A   B  C  D   
A   0   1  2  3
B   1   0  4  5
C   2   4  0  6
D   3   5  6  0

How to efficiently extract values from a large matrix, e.g. for IDs A and C to get this matrix:

    A   C    
A   0   2  
C   2   0  
 

Edit, missing IDs in the matrix should be ignored.

1 Answers

Use DataFrame.loc for get values by labels:

vals = ['A','C']

df = df.loc[vals, vals]
print (df)
   A  C
A  0  2
C  2  0

EDIT: If some values not match and need omit them add Index.intersection:

vals = ['J','A','C']

new = df.columns.intersection(vals, sort=False)
df = df.loc[new, new]
print (df)
   A  C
A  0  2
C  2  0
Related