Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make Ascending order of dates in python by considering rules?

I have a dataset like different NICs and the dates(with time) as follows.

NICS            Date and Time
1156986       8/30/2021  11:48:21 AM
1156986       7/30/2021  11:48:21 AM
1156986       6/30/2021  11:48:21 AM
1156984       5/30/2021  11:48:21 AM
1156984       4/30/2021  11:48:21 AM
1156984       3/30/2021  11:48:21 AM

I need to make these data set to ascending order but considering the NICs as well.The output should as follows,

NICS            Date and Time
1156986       6/30/2021  11:48:21 AM
1156986       7/30/2021  11:48:21 AM
1156986       8/30/2021  11:48:21 AM
1156984       3/30/2021  11:48:21 AM
1156984       4/30/2021  11:48:21 AM
1156984       5/30/2021  11:48:21 AM

So I have tried with following code, but It provide me the acending order of whole list and it has not considered the NIC.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df.sort_values(by="Date and Time", key=pd.to_datetime)

How should I get the ascending order of the dataset for each NIC value?

>Solution :

You need to sort by NIC by descending then date by ascending

s = """NICS,Date and Time
1156986,8/30/2021  11:48:21 AM
1156986,7/30/2021  11:48:21 AM
1156986,6/30/2021  11:48:21 AM
1156984,5/30/2021  11:48:21 AM
1156984,4/30/2021  11:48:21 AM
1156984,3/30/2021  11:48:21 AM"""

df = pd.read_csv(StringIO(s))

df['Date and Time'] = pd.to_datetime(df['Date and Time'])
df.sort_values(['NICS', 'Date and Time'], ascending=[False, True], inplace=True)

df
    NICS    Date and Time
2   1156986 2021-06-30 11:48:21
1   1156986 2021-07-30 11:48:21
0   1156986 2021-08-30 11:48:21
5   1156984 2021-03-30 11:48:21
4   1156984 2021-04-30 11:48:21
3   1156984 2021-05-30 11:48:21
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading