【问题标题】:Pandas Replace All Substrings in DataFramePandas 替换 DataFrame 中的所有子字符串
【发布时间】:2018-10-27 23:01:14
【问题描述】:

给定以下数据框:

import pandas as pd
d = pd.DataFrame({'A':['^|^^|^','abc'],'B':['def','^|^']})

d
        A    B
0  ^|^^|^  def
1     abc  ^|^

我需要用空格(“”)替换所有“^|^”实例。

想要的结果是:

        A    B
0           def
1     abc   

我试过这些,但没有用:

d.replace('^|^',' ') #(replaces nothing)
d.replace('^|^',' ',regex=True) #(only works for the value in column B, second row)

提前致谢!

【问题讨论】:

    标签: python-3.x pandas replace


    【解决方案1】:

    您需要转义特殊的 RegEx 符号:

    import re
    
    In [191]: d.replace(re.escape('^|^'),' ', regex=True)
    Out[191]:
         A    B
    0       def
    1  abc
    

    【讨论】:

    • 是库的方法吗?
    • @DanceParty2,它是一个模块(库)
    • @DanceParty2 或者你可以自己逃避它d.replace('\^\|\^',' ',regex=True)
    • 我不知道re.escape。这对我来说看起来更干净。我只是想提供一些@DanceParty2 可以用来更好地理解的东西......可能。很好的答案(-:只是想帮忙。
    • 谢谢!我很幸运能得到这么大的帮助。
    猜你喜欢
    • 2021-10-19
    • 2016-11-28
    • 2018-03-26
    • 2019-04-08
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多