将 Pandas 数据框中的一些列转换为列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31270635/
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:35:14  来源:igfitidea点击:

Converting some columns from pandas dataframe to list of lists

pythonpython-2.7pandas

提问by user2242044

I have a dataframe. I would like some of the data to be converted to a list of list. The columns I'm interested in are the index, Name, and Births. My code works, but it seems inefficient and for some reason the letter L is added to the end of each index.

我有一个dataframe. 我想将一些数据转换为列表列表。我感兴趣的列是indexNameBirths。我的代码有效,但似乎效率低下,并且出于某种原因将字母 L 添加到每个索引的末尾。

My code:

我的代码:

import pandas as pd


data = [['Bob', 968, 'Male'], ['Jessica', 341, 'Female'], ['Mary', 77, 'Female'], ['John', 578, 'Male'], ['Mel', 434, 'Female']]
headers = ['Names', 'Births', 'Gender']
df = pd.DataFrame(data = data, columns=headers)
indexes = df.index.values.tolist()
mylist =  [[x] for x in indexes]

for x in mylist:
    x.extend([df.ix[x[0],'Names'], df.ix[x[0],'Births']])

print mylist

Desired Output:

期望输出:

[[0, 'Bob', 968], [1, 'Jessica', 341], [2, 'Mary', 77], [3, 'John', 578], [4, 'Mel', 434]]

采纳答案by Jianxun Li

Why not just use .values.tolist()as you mentioned?

为什么不.values.tolist()按照你说的那样使用?

import pandas as pd

# your data
# =================================================
data = [['Bob', 968, 'Male'], ['Jessica', 341, 'Female'], ['Mary', 77, 'Female'], ['John', 578, 'Male'], ['Mel', 434, 'Female']]
headers = ['Names', 'Births', 'Gender']
df = pd.DataFrame(data = data, columns=headers)

# nested list
# ============================
df.reset_index()[['index', 'Names', 'Births']].values.tolist()

Out[46]: 
[[0, 'Bob', 968],
 [1, 'Jessica', 341],
 [2, 'Mary', 77],
 [3, 'John', 578],
 [4, 'Mel', 434]]

回答by Ohumeronen

Ok, this works (based on Jianxun Li's answer and comments):

好的,这是有效的(基于李建勋的回答和评论):

import pandas as pd

# Data
data = [['Bob', 968, 'Male'], ['Jessica', 341, 'Female'], ['Mary', 77, 'Female'], ['John', 578, 'Male'], ['Mel', 434, 'Female']]
headers = ['Names', 'Births', 'Gender']
df = pd.DataFrame(data = data, columns=headers)

# Output
print df.reset_index()[['index', 'Names', 'Births']].values.astype(str).tolist()

Thank you Jianxun Li, this also helped me :-)

谢谢李建勋,这也帮助了我:-)

In general, one can use the following to transform the complete dataframe into a list of lists(which is what I needed):

通常,可以使用以下内容将完整的数据框转换为列表列表(这是我需要的):

df.values.astype(str).tolist()