pandas 将熊猫数据框转换为元组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31021235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:31:21  来源:igfitidea点击:

Convert pandas dataframe to list of tuples

pythonnumpypandasdataframe

提问by psteelk

I have a sample dataframe as follows

我有一个示例数据框如下

>>> df
   a  b
0  1  2
1  3  4

I want to convert this to a list of tuples. I tried using itertuples()for the same

我想将其转换为元组列表。我尝试使用itertuples()相同的

>>> list(df.T.itertuples())
[('a', 1, 3), ('b', 2, 4)]

But, I want the result to be of the format [('a', [1, 3]), ('b', [2, 4])] wherein the first value of the tuple is the column name and the second item in the tuple is a list of column values.

但是,我希望结果的格式为 [('a', [1, 3]), ('b', [2, 4])] 其中元组的第一个值是列名,第二个值是元组中的项目是列值列表。

I know this can be done by looping through all column names and manually constructing the list of tuples. I'm just wondering if there is a smarter way to do this.

我知道这可以通过遍历所有列名并手动构建元组列表来完成。我只是想知道是否有更聪明的方法来做到这一点。

回答by EdChum

You can zip the column names with the values as lists:

您可以使用列表形式压缩列名称:

In [127]:
list(zip(df.columns,df.T.values.tolist()))

Out[127]:
[('a', [1, 3]), ('b', [2, 4])]