首页 > 解决方案 > Python pandas 替换函数不适用于转义字符

问题描述

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

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)

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

谢谢你的时间!

标签: pythonpython-3.xpandasdataframereplace

解决方案


您可以使用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

推荐阅读