如何从 pandas 对称数据框中提取元组 [英] How to extract tuples from a pandas symmetric dataframe

查看:65
本文介绍了如何从 pandas 对称数据框中提取元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示对称矩阵的数据框:

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

我要去的地方:

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

是否有使用pythonic/pandatic/代数的方式进行操作,或者我应该进行for循环?

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

谢谢.

推荐答案

df.unstack().reset_index().values

从某种意义上说,这将保留重复项,因为(a, b, 2)(b, a, 2)都将在列表中.然后,您可以在lambda t: t[0] < t[1]上进行过滤.

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].

这篇关于如何从 pandas 对称数据框中提取元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆