0

I have a list of DataFrames where I am outputting just the column names for each. I am able to sort each DataFrame by column name, but I also want to sort the list itself based on the name of the first column in each DataFrame. I've searched around but can't find what the appropriate key for sorted() would be.


for df in df_list:
        df = df.reindex(sorted(df.columns), axis=1)

sorted_dflist = sorted(df_list, key = ???)

My Output: 
( 3  4  5  8 11 12)( 7 10)( 1  6  9 13 14)(2)

Expected Output: 
( 1  6  9 13 14)(2)( 3  4  5  8 11 12)( 7 10)



mandosoft
  • 163
  • 1
  • 1
  • 8
  • 1
    Possible duplicate of [How to sort a list of lists by a specific index of the inner list?](https://stackoverflow.com/questions/4174941/how-to-sort-a-list-of-lists-by-a-specific-index-of-the-inner-list) – Yuca Nov 27 '19 at 21:31

1 Answers1

2

As I understood, the sort criterion is the first element in the first column of each DataFrame. To sort this way, try the following code:

sorted_dflist = sorted(df_list, key = lambda x: x.iloc[0,0])

To sort by the name of the first column, run:

sorted_dflist = sorted(df_list, key = lambda x: x.columns[0])
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41