如何从 pandas DataFrame 中选择含有一个或多个缺失值的行,而不必明确列名?

23 浏览
0 Comments

如何从 pandas DataFrame 中选择含有一个或多个缺失值的行,而不必明确列名?

我有一个含有大约300K行和40列的数据帧。

我想要找出是否有任何行包含null值,并将这些\'null\'-行放入单独的数据框中,以便我可以轻松地探索它们。

我可以明确创建掩码:

mask = False
for col in df.columns: 
    mask = mask | df[col].isnull()
dfnulls = df[mask]

或者我可以做类似这样的事情:

df.ix[df.index[(df.T == np.nan).sum() > 1]]

有没有更优雅的方法来定位具有null值的行呢?

admin 更改状态以发布 2023年5月24日
0
0 Comments

def nans(df): return df[df.isnull().any(axis=1)]

然后每当你需要它时,你可以输入:

nans(your_dataframe)

0
0 Comments

[已经更新以适应现代 pandas,其中将 isnull 作为 DataFrame 的方法。]

您可以使用 isnullany 来构建布尔值序列并使用它来索引您的数据框:

>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False
>>> df.isnull().any(axis=1)
0    False
1     True
2     True
3    False
4    False
dtype: bool
>>> df[df.isnull().any(axis=1)]
   0   1   2
1  0 NaN   0
2  0   0 NaN


[对于旧版的 pandas:]

您可以使用函数 isnull 而不是方法:

In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
In [57]: df
Out[57]: 
   0   1   2
0  0   1   2
1  0 NaN   0
2  0   0 NaN
3  0   1   2
4  0   1   2
In [58]: pd.isnull(df)
Out[58]: 
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False
In [59]: pd.isnull(df).any(axis=1)
Out[59]: 
0    False
1     True
2     True
3    False
4    False

导致相当紧凑的代码:

In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]: 
   0   1   2
1  0 NaN   0
2  0   0 NaN

0