Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何从数据帧内的字符串中删除多余的换行符_Regex_Python 3.x_Pandas - Fatal编程技术网

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)
+
表示前面模式的一个或多个出现,不管有多少,它们都将被一个换行符替换