Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]]
like image 381
user2242044 Avatar asked Jul 07 '15 13:07

user2242044


People also ask

How do you turn a column of a DataFrame into a list?

values. tolist() you can convert pandas DataFrame Column to List. df['Courses'] returns the DataFrame column as a Series and then use values. tolist() to convert the column values to list.

How do I turn a DataFrame into a list in Python?

To convert Pandas DataFrame to List in Python, use the DataFrame. values(). tolist() function.


1 Answers

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]]
like image 69
Jianxun Li Avatar answered Sep 19 '22 00:09

Jianxun Li