【问题标题】:Pandas 0.24 replace regex issuePandas 0.24 替换正则表达式问题
【发布时间】:2019-03-20 03:15:45
【问题描述】:

在 pandas 0.19.2 python 3.6.0 DataFrame.replace 中使用字典作用于子字符串(如“find”),Series.replace 也是如此。 Pandas 0.24.0 python 3.6.8 似乎作用于 DataFrame 的整个字符串(如“match”),但仍作用于 Series 的子字符串(如“find”)。

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

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

【问题讨论】:

  • 举报here
  • Vaishali,您链接的主题是关于一个稍微不同的问题,尽管它显然是相关的。如您所见,我的示例根本不使用整数,这就是链接问题的意义所在。这里的这个问题是关于正则表达式现在匹配整个字符串(“匹配”)与匹配子字符串(“查找”)。所有这些都是针对字符串的,不涉及整数。

标签: python pandas


【解决方案1】:

该错误列在Fixed regressions for Pandas 0.24.2

修复了DataFrame.replace() 中的回归,其中regex=True 仅替换匹配字符串开头的模式 (GH25259)

如你所见,只有

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

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

【讨论】:

  • 感谢 Wiktor,确实已验证为已修复。
猜你喜欢
  • 2011-09-07
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
相关资源
最近更新 更多