How to create a dataframe that includes all of the null values from an original dataframe?

I am hoping to create a pandas dataframe from an original dataframe that contains just rows with NA values in them

Here is an example dataframe and what I want my output to look like:

 A B C                  A B C
 2 1 Green              1 2 nan
 1 2 nan                2 1 nan
 1 1 Red        -->   
 2 1 nan
 2 1 Green

I want to be able to write my code like this, but so that is supplies me with the nan values:

df = df[df.C == 'Green']

I already have used:

df = df[df.C != 'Green']
df = df[df.C !='Red']

I am hoping for one line of code if that is possible. Thanks!

Upvotes: 2

Views: 1223

Answers (2)

Chris Adams
Chris Adams

Reputation: 18647

IIUC, use:

df[df.isna().any(1)]

   A  B    C
1  1  2  NaN
3  2  1  NaN

Upvotes: 1

Matt W.
Matt W.

Reputation: 3722

If its just one column use:

df = df[df.C.isnull()]

If its the whole dataframe (you want to filter where any column in the dataframe is null for a given row)

df = df[df.isnull().sum(1) > 0]

Upvotes: 2

Related Questions