Search code examples
pythonlistpandasdataframedata-analysis

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


Solution

  • 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']]