如何用连续数字序列替换panda数据帧中的列值



我已经从数据帧中删除了一些行,因此需要重置秩列。我已经按降序对排名列进行了排序,现在需要重新编号。有什么建议吗?

当前df:

Country   Rank  
GB        1
SGP       3
CHE       4
USA       8
IRL       9

所需df:

Country   Rank  
GB        1
SGP       2
CHE       3
USA       4
IRL       5

您可以使用以下代码:
df['Rank'] = range(1, 1+len(df))

import pandas as pd 
data = {'Country': ['GB', 'SGP', 'CHE', 'USA', 'IRL'], 'Rank': [1, 3, 4, 8, 9],} 
df = pd.DataFrame(data)
'''You can generate a list of intger range, from 1 to the length of you dataframe + 1, then overwrite your rank column with it'''
df['Rank'] = range(1,len(df)+1) 
print(df) 

最新更新