【问题标题】:Python pandas replace function not working with escaped charactersPython pandas 替换函数不适用于转义字符
【发布时间】:2020-10-01 12:59:09
【问题描述】:

我已经查看了关于 Python 3 pandas replace 函数的六个 SO 问题,但没有一个适用于这种情况。我在一些数据中有文本\",我只需要消除反斜杠。玩具代码:

import pandas as pd
df = pd.DataFrame(columns=['a'])
df.loc[0] = ['Replace \\"']
df

有输出

            a
0  Replace \"

我的目标是重写df,使其看起来像这样:

           a
0  Replace "

以下都不起作用:

df.replace('\\"', '"', regex=True)
df.replace('\\"', '\"', regex=True)
df.replace('\\\"', '\"', regex=True)
df.replace('\\\"', '\"', regex=True)
df.replace(r'\"', r'"', regex=True)
df.replace({'\\"':'"'}, regex=True)
df.replace({r'\"':r'"'}, regex=True)
df.replace(to_replace=r'\"', value=r'"', regex=True)
df.replace(to_replace=r'\"', value=r'"', regex=False)

我不能只搜索反斜杠,因为我不想替换数据中其他地方的合法反斜杠。

感谢您的宝贵时间!

【问题讨论】:

    标签: python python-3.x pandas dataframe replace


    【解决方案1】:

    你可以使用apply:

    In [2596]: df.apply(lambda x: x.str.replace(r'\\"', r'"')) 
    Out[2596]: 
               a
    0  Replace "
    

    如果只有列有问题,您也可以这样做,这样会更高效:

    In [2614]: df['a'].str.replace(r'\\"', r'"')
    Out[2614]: 
    0    Replace "
    Name: a, dtype: object
    

    【讨论】:

    • 您能否进行编辑,以便搜索反斜杠和引号?我在我的问题中提到,我不能只搜索反斜杠,因为我在数据中有合法的反斜杠。
    • 看起来df.apply(lambda x:x.str.replace(r'\\"', r'"')) 有效。
    • 是的。我更新了我的lambda 代码部分。请检查。
    • 那行不通。你需要 r 前缀来告诉它它是原始的。
    • 啊,我的错。现已更新。
    【解决方案2】:

    试试

    df.a.str.replace('\\','')
    

    结果:

    0    Replace "
    

    对于您可以使用的整个数据框:

    for col in df:
        df[col] = df[col].str.replace(r'\\','')
    

    【讨论】:

    • 正如我在原始问题和我的 cmets 中提到的,我不能只搜索反斜杠,因为我的数据中有合法的反斜杠,我不想替换。
    • 我明白了。我首先误解了这个问题。我很高兴你找到了你要找的东西。另一种实现目标的方法是 import re df.a.apply(lambda x:re.sub(r'\\"',r'"',x))。我希望这可以帮助你。干杯。
    猜你喜欢
    • 2018-11-22
    • 2018-06-24
    • 2021-08-08
    • 2016-05-22
    • 2019-05-07
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多