0

I have a dataframe, df, where I would like to rearrange row order based on column name using Pandas

Data

id  status
aa  Y
ai  N
bb  N
bc  N
dd  Y
di  Y

Desired

id  status
bb  N
dd  Y
aa  Y
ai  N
di  Y
bc  N

Doing

df.reindex([2,4,0,1,5,3])

I believe I can do an index, however, I wish to use the actual column name and values to reorder (similar to column reorder)

df = df['id'].reindex(['bb','dd','aa','ai','di', 'bc'], axis=0)
Lynn
  • 4,292
  • 5
  • 21
  • 44
  • Does this answer your question? [How to sort pandas DataFrame with a key?](https://stackoverflow.com/questions/52475458/how-to-sort-pandas-dataframe-with-a-key) – Riley Nov 01 '21 at 23:54
  • No thanks. I am not wanting a key, but moreso a specific order – Lynn Nov 01 '21 at 23:58

1 Answers1

1

I'd guess there are several ways to achieve what you want, this being one of them.

order = ['bb','dd','aa','ai','di', 'bc']
mapping = {v:k for k,v in enumerate(order)}
df.sort_values("id", key= lambda s: s.map(mapping))
Riley
  • 2,153
  • 1
  • 6
  • 16