Cody Braun
Cody Braun

Reputation: 657

Convert Pandas Distance Matrix DataFrame to Rows

I have a pandas DataFrame with n ids as columns and indices. Is there some easy method that I'm not considering to convert this to n2 rows of distances like so?

    id1 id2
id1   0 .75
id2 .75   0

to

id1   id2    .75
id1   id1      0
id2   id2      0
id2   id1    .75

Upvotes: 2

Views: 1028

Answers (1)

Alex Riley
Alex Riley

Reputation: 176730

You could use stack():

>>> df.stack()
id1  id1    0.00
     id2    0.75
id2  id1    0.75
     id2    0.00
dtype: float64

This creates a Series with a MultiIndex - the distances in your original DataFrame become the values. This generalises to any shape of DataFrame.

Upvotes: 1

Related Questions