Home > OS >  Increasing Rank based on year in pandas dataframe
Increasing Rank based on year in pandas dataframe

Time:08-11

I have two dataframes for year 2022 and year 2021 as given below:

ID  YEAR  RANK
500 2022   1
510 2022   2
520 2022   3
ID  YEAR  RANK
501 2021   1
550 2021   2
560 2021   3

I have to append year 2021 dataframe below year 2022 dataframe and reassign the rank as given in below output:

ID  YEAR  RANK
500 2022   1
510 2022   2
520 2022   3
501 2021   4
550 2021   5
560 2021   6

In above output dataframe ID which are coming in year 2021 needs to have rank more than the last rank of year 2022 dataframe i.e last rank is 3 for year 2022 so rank for first Id for year 2021 need to be 4 and so on.

CodePudding user response:

Add maximal rank to all ranks of df1 first and then use concat:

df2 = df2.assign(RANK = df2.RANK   df1.RANK.max())

df = pd.concat([df1, df2], ignore_index=True)
print (df)
    ID  YEAR  RANK
0  500  2022     1
1  510  2022     2
2  520  2022     3
3  501  2021     4
4  550  2021     5
5  560  2021     6
  • Related