如何从pandas DataFrame中选择具有一个或多个null的行,而不需要明确列出列?

331

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

我想找出是否有任何行包含空值,并将这些“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]]

有没有更优美的方法来定位包含空值的行?

6个回答

505

[已更新以适应现代的pandas,其中isnullDataFrame方法之一。]

您可以使用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

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

那么,每当你需要它时,你可以输入:

nans(your_dataframe)

1
df[df.isnull().any(axis=1)] 这个语句可以工作,但会抛出 UserWarning: Boolean Series key will be reindexed to match DataFrame index. 的警告信息。如何更明确地重写这个语句,以避免触发该警告信息? - Vishal
3
@vishal 我认为你只需要像这样添加 loc;df.loc[df.isnull().any(axis=1)] - James Draper
2
顺便提一下 - 你不应该给你的匿名(lambda)函数命名。始终使用def语句,而不是将lambda表达式直接绑定到标识符的赋值语句。 - ron_g

14

如果您想按照一定数量的空值列过滤行,可以使用以下代码:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

因此,这里有个例子:

您的数据框:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

如果你想选择那些有两列或以上为空值的行,你可以运行以下命令:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

7

字符减少了4个,但是速度增加了2毫秒

%%timeit
df.isna().T.any()
# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
df.isna().any(axis=1)
# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

我会使用 axis=1


3

.any().all()在极端情况下非常有用,但当你要寻找特定数量的空值时则不适用。这里是一种非常简单的方法来做我相信你在问什么。它非常冗长,但功能齐全。

import pandas as pd
import numpy as np

# Some test data frame
df = pd.DataFrame({'num_legs':          [2, 4,      np.nan, 0, np.nan],
                   'num_wings':         [2, 0,      np.nan, 0, 9],
                   'num_specimen_seen': [10, np.nan, 1,     8, np.nan]})

# Helper : Gets NaNs for some row
def row_nan_sums(df):
    sums = []
    for row in df.values:
        sum = 0
        for el in row:
            if el != el: # np.nan is never equal to itself. This is "hacky", but complete.
                sum+=1
        sums.append(sum)
    return sums

# Returns a list of indices for rows with k+ NaNs
def query_k_plus_sums(df, k):
    sums = row_nan_sums(df)
    indices = []
    i = 0
    for sum in sums:
        if (sum >= k):
            indices.append(i)
        i += 1
    return indices

# test
print(df)
print(query_k_plus_sums(df, 2))

输出

   num_legs  num_wings  num_specimen_seen
0       2.0        2.0               10.0
1       4.0        0.0                NaN
2       NaN        NaN                1.0
3       0.0        0.0                8.0
4       NaN        9.0                NaN
[2, 4]

如果你和我一样,想要清除那些行,你只需写入以下代码:

# drop the rows from the data frame
df.drop(query_k_plus_sums(df, 2),inplace=True)
# Reshuffle up data (if you don't do this, the indices won't reset)
df = df.sample(frac=1).reset_index(drop=True)
# print data frame
print(df)

输出:

   num_legs  num_wings  num_specimen_seen
0       4.0        0.0                NaN
1       0.0        0.0                8.0
2       2.0        2.0               10.0

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接