Replace frame order according to values in row

Viewed 17

If I have the following dataframe:

import pandas as pd
df = {'Status': {0: 'Available',
1: 'Collect',
2: 'Failed',
3: 'Delivered',
4: 'Totaal',
5: 'sent out',
6: 'received',
7: 'Not yet executed',
8: 'received',
9: 'Approved'},
'Aantal': {0: 5,
1: 25,
2: 35,
3: 55,
4: 105,
5: 65,
6: 75,
7: 95,
8: 55,
9: 505}}
df = pd.DataFrame(df)

And I would like to re-arrange the order of the dataframe. So instead of the first row; 'Available', I would like Collect.

How can I do this?

Thank you in advance.

1 Answers

A robust way might be to sort using inequality to "Collect" as key and a stable sort:

out = df.sort_values('Status', key=lambda s: s.ne('Collect'), kind='stable')

Other option, using slicing and concat:

m = df['Status'].eq('Collect')
out = pd.concat([df[m], df[~m]])

output:

             Status  Aantal
1           Collect      25
0         Available       5
2            Failed      35
3         Delivered      55
4            Totaal     105
5          sent out      65
6          received      75
7  Not yet executed      95
8          received      55
9          Approved     505
Related