用空格替换熊猫数据框单元格中的空行

时间:2020-05-21 01:09:50

标签: python regex pandas dataframe

提取到数据框中的

API数据在少数注释单元格中包含空白值。我最终希望将数据帧加载到csv文件中。当我将数据帧加载到csv时,注释中的空白行将被视为新行,从而在csv中给出错误的行数。

数据框:

Employee_id | Employeee_comments
---------------------------------------
1           | 1. This is test comment 1
            | 2. This is test comment 2
            |
            | Comments above employee above
---------------------------------------------
2           | 1. This is test comment 3 

我尝试在数据帧上使用正则表达式替换,但是替换了单词之间的空格。

df = df.replace('\s+', '',regex=True)

请告知我如何用空格替换空白行,以使输出看起来像下面-

Employee_id | Employee_comments
--------------------------------
1           | 1. This is test comment 1 2. This is test comment 2 Comments above employee above
2           | 1. This is test comment 3

1 个答案:

答案 0 :(得分:0)

我认为您可以使用\n+代替\s+,并用空格替换空字符串:

df = df.replace(r'\n+', ' ', regex=True)

\n仅替换新行。 \s替换新行,空格和制表符。