Python,Pandas:仅返回缺少值的行

问题描述 投票:28回答:2

在Python中使用Pandas时...

我正在使用包含一些缺失值的数据集,并且我想返回一个仅包含缺少数据的行的数据框。有一个很好的方法来做到这一点?

(我目前的方法是效率低下“看看没有缺失值的数据框中没有索引,然后从这些索引中生成一个df。”)

python pandas missing-data
2个回答
67
投票

您可以使用any axis=1检查每行至少一个True,然后使用boolean indexing过滤:

null_data = df[df.isnull().any(axis=1)]

0
投票

与meterk的回答类似,

null_data = df[np.logical_or.reduce(df.isnull(), axis=1)]

测试

n = 2
df = pd.DataFrame({'a':np.tile([0,1,2,3,4,np.nan],n),
                   'b':np.tile([0,1,2,3,np.nan,5],n)})

x = df[np.logical_or.reduce(df.isnull(),axis=1)]
y = df[df.isnull().any(axis=1)]
x.equals(y)
© www.soinside.com 2019 - 2024. All rights reserved.