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?
CodePudding user response:
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
CodePudding user response:
You can try factorize
df['new'] =df.Time.factorize()[0] 1
df
Out[463]:
ID Time new
0 0 100 1
1 1 100 1
2 2 200 2
3 3 200 2
4 4 500 3
5 5 500 3
6 6 890 4