Regex 如何从数据帧内的字符串中删除多余的换行符
我的目的是从数据帧内的字符串中删除不必要的换行符 示例:Regex 如何从数据帧内的字符串中删除多余的换行符,regex,python-3.x,pandas,Regex,Python 3.x,Pandas,我的目的是从数据帧内的字符串中删除不必要的换行符 示例: import pandas as pd data = ['I like this product\n\nThe product is good'] dataf = pd.DataFrame(data) 原始数据: I like this product The product is good 我尝试了下面的方法,但没有成功,因为所有的换行符都被删除了,而我想保留其中一个 dataf['new'] = dataf.replace('
import pandas as pd
data = ['I like this product\n\nThe product is good']
dataf = pd.DataFrame(data)
原始数据:
I like this product
The product is good
我尝试了下面的方法,但没有成功,因为所有的换行符都被删除了,而我想保留其中一个
dataf['new'] = dataf.replace('\\n','', regex=True)
结果是,删除了所有换行符:
I like this productThe product is good
我试图实现的结果是:
I like this product
The product is good
这应该可以:
dataf['new'] = dataf.replace(r'(\n)+', r'\n', regex=True)
+
表示前面模式的一个或多个出现,不管有多少,它们都将被一个换行符替换