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]]
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.
To convert Pandas DataFrame to List in Python, use the DataFrame. values(). tolist() function.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With