简体   繁体   中英

Converting some columns from pandas dataframe to list of lists

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.

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

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

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM