Home > Net >  Rearrange row order based on column name using Pandas
Rearrange row order based on column name using Pandas

Time:11-02

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)

CodePudding user response:

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))
  • Related