Home > database >  Convert all columns in pandas dataframe into a nested list
Convert all columns in pandas dataframe into a nested list

Time:02-21

I have a data frame time_df and I want to convert all 147 columns in time_df into a nested list with 147 lists.

I know it can be done on the rows by time_df.values.tolist() but how can I create a nested list where values in column V1 is a list, values in V2 is a list all the way to V147.

time_df.head()
                    V1  ...                 V147
0  02-06-22T00:00.000Z  ...  11-22-18T00:00.000Z
1  02-07-22T00:00.000Z  ...  11-23-18T00:00.000Z
2  02-08-22T00:00.000Z  ...  11-24-18T00:00.000Z
3  02-09-22T00:00.000Z  ...  11-25-18T00:00.000Z
4  02-10-22T00:00.000Z  ...  11-26-18T00:00.000Z
[5 rows x 147 columns]

Desired output

# nested list 
[['2022-02-06T00:00:00.000Z', '2022-02-07T00:00:00.000Z', '2022-02-08T00:00:00.000Z', '2022-02-09T00:00:00.000Z', '2022-02-10T00:00:00.000Z', '2022-02-11T00:00:00.000Z', '2022-02-12T00:00:00.000Z', '2022-02-13T00:00:00.000Z', '2022-02-14T00:00:00.000Z', '2022-02-15T00:00:00.000Z', '2022-02-16T00:00:00.000Z'], 
... 145 list between ... 
['2018-11-22T00:00:00.000Z', '2018-11-23T00:00:00.000Z', '2018-11-24T00:00:00.000Z', '2018-11-25T00:00:00.000Z', '2018-11-26T00:00:00.000Z', '2018-11-27T00:00:00.000Z', '2018-11-28T00:00:00.000Z', '2018-11-29T00:00:00.000Z', '2018-11-30T00:00:00.000Z', '2018-12-01T00:00:00.000Z', '2018-12-02T00:00:00.000Z']]

CodePudding user response:

You need transpose before converting to list:

time_df.T.values.tolist()

For new pandas versions use:

time_df.T.to_numpy().tolist()
  • Related