Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert my dataframe to a 2d list with all column as a list

I have a df,

Name  Class
Sri   A
Ram   B

My expected output is

 [["Name","Sri","Ram"],["Class","A","B"]]

I tried df.values.tolist() but gives row wise lists, I need it in column wise. Thanks in advance

like image 758
Vicky Avatar asked Jan 04 '23 02:01

Vicky


1 Answers

Use transpose:

print (df.values.T.tolist())
[['Sri', 'Ram'], ['A', 'B']]

If need also columns names first transpose by T with reset_index:

print (df.T.reset_index().values.tolist())
[['Name', 'Sri', 'Ram'], ['Class', 'A', 'B']]

EDIT: For remove NaNs use list comprehension:

print (df)
  Name Class
0  Sri     A
1  Ram   NaN

L = df.values.T.tolist()
print (L)
[['Sri', 'Ram'], ['A', nan]]

L1 = [[i for i in x if pd.notnull(i)] for x in L]
print (L1)
[['Sri', 'Ram'], ['A']]
like image 127
jezrael Avatar answered Jan 25 '23 10:01

jezrael