Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count NaNs when using value_counts() on a dataframe

Tags:

python

pandas

nan

I want to count the number of occurrences over two columns of a DataFrame :

No Name
1   A  
1   A
5   T
9   V
Nan M
5   T
1   A

I expected df[["No", "Name"]].value_counts() to give

No Name Count
1   A     3
5   T     2
9   V     1
Nan M     1

But I am missing the row containing NaN.

Is there a way to include NaNs in value_counts()?

like image 597
Pete Avatar asked Sep 05 '25 03:09

Pete


1 Answers

You can still use value_counts() but with dropna=False rather than True (the default value), as follows:

df[["No", "Name"]].value_counts(dropna=False)

So, the result will be as follows:

   No   Name    size
0   1     A     3
1   5     T     2
2   9     V     1
3   NaN   M     1
like image 132
Taie Avatar answered Sep 07 '25 23:09

Taie