【问题标题】:Pandas dataframe regex replace not working in new version熊猫数据框正则表达式替换在新版本中不起作用
【发布时间】:2021-08-02 11:47:28
【问题描述】:

此代码用于旧版 pandas (0.24.2),但在当前版本 (1.3.0) 中引发错误:*ValueError: Series.replace cannot use dict-like to_replace and non-None value*。
import pandas as pd

a = pd.DataFrame([['the quick red fox jumps over the lazy dog','red|over'],['red is the color for danger','red']], columns=['text','match'])
a['text'].replace(r'('+a['match']+')', r'<*\1*>', regex=True, inplace=True)

print(a)

如何让它在较新的版本上运行?

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    IIUC:

    尝试:

    a['text']=a['text'].replace('('+'|'.join(a['match'].tolist())+')', r'<*\1*>', regex=True)
    

    a的输出:

        text                                                  match
    0   the quick <*red*> fox jumps <*over*> the lazy dog   red|over
    1   <*red*> is the color for danger                      red
    

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2017-05-19
      • 2022-08-18
      • 2020-10-23
      • 1970-01-01
      相关资源
      最近更新 更多