Create Series by applying function over every df column

Viewed 27

Given a DataFrame, I'd like to count the number of NaN values in each column, to show the proportion as a histogram.

I've come up with

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
nan_dict = {}
for col in df:
    nan_dict[col] = df[col].value_counts(dropna=False)[0]

and then build the histogram from the dict. This seems really cumbersome; also, it fails when there are no NaNs.

Is there a way I could apply value_counts along all columns so that I get back a Series with NaN values per column?

1 Answers
df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
print(dict(zip(df.columns, df.isna().sum())))

Prints:

{'col1': 0, 'col2': 0}

For dataframe:

   col1  col2
0     1   3.0
1     2   NaN

Prints:

{'col1': 0, 'col2': 1}
Related