How to extract tuples from a pandas symmetric data

2019-05-31 05:00发布

问题:

I have a dataframe representing a symmetric matrix:

  a b c d
a   2 3 4
b 2   6 8
c 3 6   5
d 4 8 5

From where I want to go to:

[(a,b,2),(a,c,3),(a,d,4),(b,c,6),...]

Is there a pythonic/pandatic/ algebraic way of doing it or I should go of for loops?

Thank you.

回答1:

df.unstack().reset_index().values

This will keep duplicates in a sense that both (a, b, 2) and (b, a, 2) will be in the list. You can then filter on lambda t: t[0] < t[1].