这是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/