1

I have a long list of named Pandas data frames. My goal is to sort this list alphabetically by the names of the data frames. Here is a MWE:

import pandas as pd    
df_1 = pd.DataFrame(None)
df_1.name = 'a'
df_2 = pd.DataFrame(None)
df_2.name = 'b'
df_3 = pd.DataFrame(None)
df_3.name = 'c'
df_list = [df_2, df_1, df_3]

Now, my goal is to sort df_list such that I get a new list [df_1, df_2, df_3] reflecting the alphabetical order of the names of the data frames.

Umar.H
  • 22,559
  • 7
  • 39
  • 74
Joe
  • 1,628
  • 3
  • 25
  • 39
  • 1
    You can use `key` for the built-in `sorted`. `df_sorted = sorted(df_list, key=lambda x: x.name)` – DOOM Mar 20 '20 at 18:36
  • This works as expected! If you make it a real answer, I accept it. – Joe Mar 20 '20 at 18:39
  • 1
    Does this answer your question? [How to sort a list of objects based on an attribute of the objects?](https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – AMC Mar 20 '20 at 18:59

1 Answers1

3

With built-in sorted

df_sorted = sorted(df_list, key=lambda x: x.name)
DOOM
  • 1,170
  • 6
  • 20