Home > Back-end >  Reordering index column according to date in Pandas dataframe
Reordering index column according to date in Pandas dataframe

Time:10-03

I have a dataframe that is sorted in descending order of date but the ID is not necessarily in ascending order, it looks something like (Note that some IDs might have the same date):

ID  Date  
1   2022-05-13
1   2022-05-13
1   2022-05-13
3   2022-05-13
3   2022-05-13
3   2022-05-13
3   2022-05-13
16  2022-07-14
16  2022-07-14
16  2022-07-14
2   2022-07-14
2   2022-07-14
2   2022-07-14
2   2022-07-14
2   2022-07-14
2   2022-07-14
9   2022-08-11
9   2022-08-11

And I would like to reorder the ID column so that the ID is in ascending column (so it preserves the number of rows of the original IDs), i.e.

ID  Date  
1   2022-05-13
1   2022-05-13
1   2022-05-13
2   2022-05-13
2   2022-05-13
2   2022-05-13
2   2022-05-13
3   2022-07-14
3   2022-07-14
3   2022-07-14
4   2022-07-14
4   2022-07-14
4   2022-07-14
4   2022-07-14
4   2022-07-14
4   2022-07-14
5   2022-08-11
5   2022-08-11

Thank you so much in advance.

CodePudding user response:

Try:

df.sort_values(by='ID').reset_index(drop=True)

CodePudding user response:

Try this;

df["ID"] = sorted(list(df["ID"]))
  • Related