Skip to main content
 首页 » 编程设计

python之将 pandas 数据框中列中的 # 值替换为按行自动递增的值

2024年11月01日11birdshome

场景是:VendorID 列在 pandas 数据帧的所有行中都包含“#”。 我一直在尝试将 VendorID 列中“#”的值替换为自动递增行号值。

我正在尝试 str.replace() 函数:

data['VendorID'].str.replace(r'[#]', replacing_value) 

我想弄清楚我应该在上面的行中写什么来代替 replacing_value

目前显示如下:

VendorID 
# 
# 
# 
. 
. 

预期:

VendorID 
0 
1 
2 
3 
. 
. 
. 

请您参考如下方法:

df['VendorID']= pd.Series(range(1,df.shape[0]+1)) #starts with 1 

或

df['VendorID']= pd.Series(range(0,df.shape[0])) #starts with 0