简体   繁体   English

如何用一系列连续数字替换 pandas 数据框中的列值?

[英]How can I replace the column values in a pandas data frame with a sequence of consecutive numbers?

I have removed some rows from my dataframe and therefore need to reset the rank column.我从 dataframe 中删除了一些行,因此需要重置排名列。 I have sorted the rank column in descending order and now need to redo the numbering.我已按降序对排名列进行排序,现在需要重做编号。 Any suggestions?有什么建议么?

Current df:当前 df:

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

Desired df:所需的 df:

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

You can use below code:您可以使用以下代码:
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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM