python - 如何替换 '..' 和 '?.' 熊猫中有单个句点和问号?df['column'].str.replace 不起作用
问题描述
这是此 SO 帖子的后续内容,它提供了替换字符串列中的文本的解决方案
df['range'] = df['range'].str.replace(',','-')
但是,这似乎不适用于双句号或问号后跟句号
testList = ['this is a.. test stence', 'for which is ?. was a time']
testDf = pd.DataFrame(testList, columns=['strings'])
testDf['strings'].str.replace('..', '.').head()
结果是
0 ...........e
1 .............
Name: strings, dtype: object
和
testDf['strings'].str.replace('?.', '?').head()
结果是
error: nothing to repeat at position 0
解决方案
添加regex=False
参数,因为正如您在文档中看到的那样,正则表达式默认为 True:
-regex bool , 默认为 True
确定是否假定传入的模式是正则表达式:如果为 True,则假定传入的模式是正则表达式。
并且? .
是正则表达式中的特殊字符。
因此,没有正则表达式的一种方法是这种双重替换:
testDf['strings'].str.replace('..', '.',regex=False).str.replace('?.', '?',regex=False)
输出:
strings
0 this is a. test stence
1 for which is ? was a time
推荐阅读
- kubernetes - 使用 minikube NGINX 入口连接到 websocket 服务器时出错
- powershell - 通过导出 .csv 文件,通过 Powershell 将禁用的用户移动到 AD 中的 OU
- python - 用于回归的 KNN
- graphql - 类型应该使用 Apollo Graphql 引用特定的枚举或联合
- javascript - 当且仅当有 2 行或更多行要显示时,如何缩进第一行?
- windows - 如何让背景图像显示在 Windows Mail 10 应用程序中?
- python - while 循环不会对齐并继续代码并继续循环
- python - 简单邮件传输协议脚本错误
- r - 使用数据字典应用值替换
- c# - 从字典中获取前 n 个值的最佳方法是什么?