如何移除DataFrame中的空行?使用dropna未获预期结果求助
正确移除DataFrame中的空行
问题场景
我有如下带有空行的DataFrame:
Type Channel Agt 0 1 ServiceList DCS 2 3 4 ServiceList WEB 5 6 7 ServiceSearch TA 95AKSJAPI
期望输出为:
Type Channel Agt 0 ServiceList DCS 1 ServiceList WEB 2 ServiceSearch TA 95AKSJAPI
我尝试使用df.dropna(inplace=True),得到的输出却是:
Type Channel Agt 0 ServiceSearch TA 95AKSJAPI
原因分析
那些看起来是空的行,并非真正的NaN值,而是空字符串或仅包含空格的字符串。dropna()仅会移除含NaN的行,因此无法处理这类场景。
解决方案
方法1:先替换空内容为NaN再删除
import pandas as pd import numpy as np # 将所有空字符串/仅含空格的内容替换为NaN df = df.replace(r'^\s*$', np.nan, regex=True) # 删除含NaN的行 df.dropna(inplace=True) # 重置索引(让索引从0开始连续,可选) df.reset_index(drop=True, inplace=True)
方法2:直接过滤非空行
通过判断每行是否所有元素都是空/空格来过滤:
# 过滤掉所有元素均为空/空格的行 df = df[~df.apply(lambda x: x.str.strip().eq('').all(), axis=1)] # 重置索引 df.reset_index(drop=True, inplace=True)
执行上述任意一种方法后,即可得到预期的输出结果。
内容的提问来源于stack exchange,提问作者Rejoy
相关产品推荐
相关产品推荐

