Home > Net >  Pandas df: Sort by index based on custom list
Pandas df: Sort by index based on custom list

Time:09-16

I am using pandas=1.1.5

I want to sort a df based on index by a custom list.
The custom list

  1. may not have all the index values of the df
  2. may have extra values not in df

Example: Firm AC is not in ordered list. Firm AA & C are in ordered list but not in df index

|       | Revenue  |Cost  |
|Firm AC| 1        |2     |
|Firm B | 6        |3     |
|Firm ZZ| 0        |10    |

Ordered_list= [Firm AA, Firm ZZ, Firm C, Firm B]


After sorting

|       | Revenue  |Cost  |
|Firm ZZ| 0        |10    |
|Firm B | 6        |3     |
|Firm AC| 1        |2     |

How to do so? Thanks!

CodePudding user response:

Let's use sort_values with a custom sort dictionary:

# create dictionary with key as firm, value as order in the list
ordered_dict = {k: i for i, k in enumerate(Ordered_list)}

# sort by index with the created dictionary
df.sort_index(key=lambda x: x.map(ordered_dict))
  • Related