将pandas数据框转换为元组列表-(“行”,“列”,值) [英] Convert pandas dataframe to list of tuples - ('Row', 'Column', Value)

查看:175
本文介绍了将pandas数据框转换为元组列表-(“行”,“列”,值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于同一主题,还有其他一些问题,但是所需的格式完全不同。

There are a few other questions regarding the same subject, but the format desired is different in all.

我正在尝试使用整体景观和散景

我的数据作为Excel文件读入数据框,类似于以下内容:

My data is being read in as an Excel file into a dataframe to something along the lines of:

    Foo    Bar    Bash    Baz   ...
A   1      2      3       4
B   2      1      0       3
C   0      0      2       0
D   2      3      5       1
...

文档说 HeatMap的数据可以作为2D表格数据提供,一个或多个关联的值维度。

绘制数据框本身不起作用,我觉得我需要将数据整理成表格像这样:

Plotting the dataframe itself doesn't work, I feel like I need to get my data into a form like:

[('A', 'Foo', 1), ('A', 'Bar', 2), ('A', 'Bash', 3), ('A', 'Baz', 4), ('B', 'Foo', 1)...]

比手动遍历整个数据帧并手动构建它有更快的方法吗?

Is there a faster way to do this than manually iterating through the entire dataframe and building it manually?

推荐答案

您可以先通过 stack进行重塑 ,然后转换为元组 s:

tups = [tuple(x) for x in df.stack().reset_index().values.tolist()]

另一个类似的解决方案是创建3个级别 MultiIndex

Another similar solution is create 3 levels MultiIndex:

tups = df.stack().to_frame().set_index(0, append=True).index.tolist()

zip 3个单独的 array s和 numpy.repeat numpy.tile ravel

Or zip 3 separately arrays with numpy.repeat, numpy.tile and ravel:

a = np.repeat(df.index, len(df.columns))
b = np.tile(df.columns, len(df))
c = df.values.ravel()

tups = list(zip(a,b,c))

这篇关于将pandas数据框转换为元组列表-(“行”,“列”,值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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