简体   繁体   中英

How to convert a Python Dataframe to List of Lists?

I have a dataframe in Python of dimensions 21392x1972. What I would like to accomplish is to convert the data frame into a list of lists, such that the first column of my data frame is the first list within the long list, second column of data frame the second list with the one long list and so on.

I tried to use tolist() to convert the data frame to a list of lists. What is happening now is that each row of my data frame is becoming one list within the long list. But, what I would like to accomplish is that each column of data frame should become one list within the long list. I am new to using Pandas and Python, so any help in this regard is highly appreciated. Cheers!

import pandas as pd
mydataset = pd.read_csv('final_merged_data.csv')
mydataset_seq = mydataset.values.tolist() 

Loop through all columns in your dataframe, index that column, and convert it to a list:

lst = [df[i].tolist() for i in df.columns]

Example:

df = pd.DataFrame({'a' : [1, 2, 3, 4],
'b' : [5, 6, 7, 8]})

print(df)
print('list', [df[i].tolist() for i in df.columns])

Output:

   a  b
0  1  5
1  2  6
2  3  7
3  4  8
'list' [[1, 2, 3, 4], [5, 6, 7, 8]]

换位

mydataset_seq = mydataset.T.values.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