Skip to main content
 首页 » 编程设计

python之Pandas 0.24 替换正则表达式问题

2024年12月31日27yjmyzz

对于 pandas 0.19.2 python 3.6.0 DataFrame.replace 和字典作用于子字符串(如“find”),Series.replace 也是如此。 Pandas 0.24.0 python 3.6.8 似乎作用于数据帧的整个字符串(如“匹配”),并且仍然作用于系列的子字符串(如“查找”)。

df = pd.DataFrame({'c1':['AD','BD'],'c2':['AD','BD']}) 
print(df) 
print(df.replace(to_replace={'c1':{r'D': ''}, 'c2':{r'BD': ''}},regex=True)) 
print(df.replace(to_replace={r'D': ''},regex=True)) 
print(df['c1'].replace(to_replace=r'D', value='',regex=True)) 

Pandas 0.19.2 生成(为了易读性我添加了一些空行):

   c1  c2 
0  AD  AD 
1  BD  BD 
 
  c1  c2 
0  A  AD 
1  B     
 
  c1 c2 
0  A  A 
1  B  B 
 
0    A 
1    B 
Name: c1, dtype: object 

使用 Pandas 0.24.0:

   c1  c2 
0  AD  AD 
1  BD  BD 
 
   c1  c2 
0  AD  AD 
1  BD     
 
   c1  c2 
0  AD  AD 
1  BD  BD 
 
0    A 
1    B 
Name: c1, dtype: object 

在我看来像是 Pandas 虫,还是我遗漏了什么?

请您参考如下方法:

错误列在 Fixed regressions for Pandas 0.24.2 中:

Fixed regression in DataFrame.replace() where regex=True was only replacing patterns matching the start of the string (GH25259)

如你所见,只有

print(df.replace(to_replace={'c1':{r'D': ''}, 'c2':{r'BD': ''}},regex=True)) 
print(df.replace(to_replace={r'D': ''},regex=True)) 

没有正常工作。现在,问题已解决。