我已经研究了关于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)
我不能只搜索反斜杠,因为在数据中我不想替换的其他地方都有合法的反斜杠。
感谢您的时间!
答案 0 :(得分:2)
您可以使用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
答案 1 :(得分:0)
尝试
df.a.str.replace('\\','')
结果:
0 Replace "
对于整个数据框,您可以使用:
for col in df:
df[col] = df[col].str.replace(r'\\','')