Counting NaN in specific columns in a dataframe

Viewed 36

I have a dataframe that looks a little bit like this

 A   B   C   D    E   F   G   H
100 100 NaN 100 1000 NaN NaN NaN

I'm trying to count the instances of NaN in columns A-D; and then columns E-H

What I've tried is:

df_["NaN_A-D"] = df[["A", "B", "C", "D"]].isna().sum()
df_["NaN_E-H"] = df[["E", "F", "G", "H"]].isna().sum()

But the new column just returns NaN rather than summing up the instances of NaN (ie 1 for the first grouping and 3 for the second grouping.

What am I doing wrong, please?

Thanks

1 Answers

You need axis=1 because need sum per rows, also output is assigned to same DataFrame df:

df["NaN_A-D"] = df[["A", "B", "C", "D"]].isna().sum(axis=1)
df["NaN_E-H"] = df[["E", "F", "G", "H"]].isna().sum(axis=1)
print (df)
     A    B   C    D     E   F   G   H  NaN_A-D  NaN_E-H
0  100  100 NaN  100  1000 NaN NaN NaN        1        3
Related