python - 如何用 Pandas 中的单个句点和问号替换 '..' 和 '?.'? df ['column' ].str.replace 不起作用

标签 python pandas

这是this SO post的后续,它提供了替换字符串列中的文本的解决方案
How to replace text in a column of a Pandas dataframe?

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参数,因为正如您在 docs 中看到的那样, 正则表达式默认为 True:

-regex bool, default True


Determines if assumes the passed-in pattern is a regular expression: If True, assumes the passed-in pattern is a regular expression.


? .是正则表达式中的特殊字符。
因此,没有正则表达式的一种方法是双重替换:
testDf['strings'].str.replace('..', '.',regex=False).str.replace('?.', '?',regex=False)
输出:
                     strings
0     this is a. test stence
1  for which is ? was a time

关于python - 如何用 Pandas 中的单个句点和问号替换 '..' 和 '?.'? df ['column' ].str.replace 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63142312/

相关文章:

python - Pandas 数据框。更改 float 格式。保留类型 "float"

python - 如何在 Python 中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为 x 轴上的标签?

python - 保留电子邮件域但删除 TLD

python - 运行 FTP.retrbinary 检索文件时出错

python - 检查 Samba 上的符号链接(symbolic link)是否与 python 共享

python - pyqt4按钮点击处理程序

python - Mitmproxy 允许远程连接/禁用 block_global

python - 根据另一列的下一个值更改 Pandas 日期时间列

python - 如何完全重置警告

python - Pandas:在半重叠的列上连接两个数据框