-1

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.

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?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
veganbu chat
  • 106
  • 11

1 Answers1

2

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
Epsi95
  • 8,832
  • 1
  • 16
  • 34