Can I modify pd.Series.value_counts so that by default `dropna=False`?

Viewed 56

When using pd.Series.value_counts I almost always add the parameter dropna=False. Is there a simple way to set this as the default value without creating a separate function?

I (among others) am also curious about an explanation for why the default value is set to True in the first place.

import pandas as pd; import numpy as np

# initialize series
s = pd.Series([1,1,2,3,np.nan])

# would like s.value_counts() to have the same output as s.value_counts(dropna=False)
s.value_counts(dropna=False)
1 Answers

You can check the parameters of pd.Series.value_counts:

print(pd.Series.value_counts.__annotations__)
# Ouput
{'normalize': 'bool', 'sort': 'bool', 'ascending': 'bool', 'dropna': 'bool'}

And the associated default values:

print(pd.Series.value_counts.__defaults__)
# Ouput
(False, True, False, None, True)

So, you can change them so that the default value for dropna becomes False:

pd.Series.value_counts.__defaults__ = (False, True, False, None, False)

print(s.value_counts())
# Output
1.0    2
2.0    1
3.0    1
NaN    1
Related