2

Suppose I have a dataframe with columns b. and c., I want to sort the dataframe by column b. in ascending order, and by column c. based on the order of a list, how do I do this?

Original df:

b.  c.
A   BA
A   PY
B   CH
A   CH
B   BA
C   BA
B   PY
C   PY

sort ascending for the "b." column and for "c." cloumn sort based on this list:

["PY","BA","MA","CH"]

so result should look something like this:

b.  c.
A   PY
A   BA
A   CH
B   PY
B   BA
B   CH
C   PY
C   CH
Data_sniffer
  • 588
  • 1
  • 8
  • 19
  • 1
    sorter = ["PY","BA","MA","CH"]; df['c.'] = df['c.'].astype("category"); df['c.'].cat.set_categories(sorter, inplace=True); sorted_df = df.sort_values(['b.','c.']) – Derek O May 20 '20 at 18:44
  • 1
    @DerekO this deserves to be the right answer for my question. dude thank you so much – Data_sniffer May 20 '20 at 18:53
  • 1
    Yeah I was about to post it before your question got closed! Glad to be of help anyway :) – Derek O May 20 '20 at 22:56

0 Answers0