python - 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)
我不能只搜索反斜杠,因为我不想替换的数据中的其他地方有合法的反斜杠。
谢谢你的时间!
解决方案
您可以使用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
推荐阅读
- typescript - 如何修复错误“参数'state'和'state'的类型不兼容”
- c++ - 如何对主对角线上方的二维数组中的元素进行排序
- css - 淡出 CSS 中的新行
- asp.net-mvc - 有没有办法将 IEnumerable 参数传递给另一个方法
- php - Mysql在一个语句中多次更新
- excel - VBA for Excel 根据连续行中的文本插入行
- java - 允许用户输入具有相同名称的变量
- c++ - 如何对传入可变参数宏的可变参数求和?
- node.js - 你可以在 install4j 中使用 nodejs
- amazon-web-services - 有没有办法通过 AWS-CLI 在 Lambda 中设置 Amazon S3 链接 URL?