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
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 NaN
s 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']]
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