I have a dataframe like this:
ID Time
0 100
1 100
2 200
3 200
4 500
5 500
6 890
...
I want to add a column of ordinal number based on column ‘Time’ in ascending order, like this:
ID Time Ordinal
0 100 1
1 100 1
2 200 2
3 200 2
4 500 3
5 500 3
6 890 4
...
Is there any elegant way to do this?
>Solution :
You could use pd.dataframe.rank:
>>> df["Ordinal"] = df["Time"].rank(method="dense") # Optionally, add .astype(int) to cast to int
>>> df
ID Time Ordinal
0 0 100 1.0
1 1 100 1.0
2 2 200 2.0
3 3 200 2.0
4 4 500 3.0
5 5 500 3.0
6 6 890 4.0