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)



1

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Edited above. It should be sorted by the name of the first column in each DataFrame.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.