1

I have a dataframe like this

Name    values   Status          CompletedOn
ac       100    Pending      2019-01-10T03:59:42.184+00:00
as       10     Pending      2019-06-10T03:59:42.184+00:00
sd       10     Closed       2019-12-10T03:59:42.184+00:00
es       10     Closed       2019-12-11T03:59:42.184+00:00
sg       5      Closed       2020-12-10T03:59:42.184+00:00
er       10     optional     2019-12-14T03:59:42.184+00:00
rw       10     optional     2019-12-15T03:59:42.184+00:00

I want to sort them on the basis if list vals=['pending','optional','Closed'] and Completed on Date corresponding to the status.

I have tried sorting by a custom list in pandas but unable to figure out the method to sort them on basis of date also.

So the output Dataframe would be like

Name    values   Status          CompletedOn
ac       100    Pending      2019-06-10T03:59:42.184+00:00
as       10     Pending      2019-01-10T03:59:42.184+00:00
er       10     optional     2019-12-15T03:59:42.184+00:00
rw       10     optional     2019-12-14T03:59:42.184+00:00
sg       5      Closed       2020-12-10T03:59:42.184+00:00
es       10     Closed       2019-12-11T03:59:42.184+00:00
sd       10     Closed       2019-12-10T03:59:42.184+00:00

any help please ?

Eklavya
  • 17,618
  • 4
  • 28
  • 57
R.singh
  • 259
  • 1
  • 13

1 Answers1

1

Give this a go, and see if it fits ur use case:

The idea is to get the Status column as a category data type, with the category orders included in the conversion. You can then sort on both Status and CompletedOn, and include the ascending parameters

#convert Status to category dtype
df.Status = pd.Categorical(df.Status, categories = ['Pending','optional','Closed'])

#sort columns with ascending options for the columns
df.sort_values(['Status', 'CompletedOn'],ascending = [True,False])

      Name  values   Status            CompletedOn
1     as    10      Pending     2019-06-10 03:59:42.184000+00:00
0     ac    100     Pending     2019-01-10 03:59:42.184000+00:00
6     rw    10     optional     2019-12-15 03:59:42.184000+00:00
5     er    10     optional     2019-12-14 03:59:42.184000+00:00
4     sg    5      Closed       2020-12-10 03:59:42.184000+00:00
3     es    10     Closed       2019-12-11 03:59:42.184000+00:00
2     sd    10     Closed       2019-12-10 03:59:42.184000+00:00
sammywemmy
  • 27,093
  • 4
  • 17
  • 31