首页 > 解决方案 > 如何替换 '..' 和 '?.' 熊猫中有单个句点和问号?df['column'].str.replace 不起作用

问题描述

这是此 SO 帖子的后续内容,它提供了替换字符串列中的文本的解决方案

如何替换 Pandas 数据框列中的文本?

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

标签: pythonpandas

解决方案


添加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

推荐阅读