is there a way to change the default parameter of pandas.value_counts(dropna=False) method in a Jupyter notebook for all the occasions that it is called?
I have tried to use a wrapper function but would rather the default method
def my_value_counts(series, dropna=False, *args, **kwargs):
return series.value_counts(dropna=dropna, *args, **kwargs)
In python, you can change the default signature of a function or method even for existing instances:
import pandas as pd
import numpy as np
import inspect
sr = pd.Series(np.random.choice([1, np.nan], 10))
# Default behavior
print(inspect.signature(sr.value_counts))
print(sr.value_counts())
# This is the trick
pd.Series.value_counts.__defaults__ = (False, True, False, None, False)
# New behavior
print(inspect.signature(sr.value_counts))
print(sr.value_counts())
Output:
(normalize: 'bool' = False, sort: 'bool' = True, ascending: 'bool' = False, bins=None, dropna: 'bool' = True) -> 'Series'
1.0 6
dtype: int64
(normalize: 'bool' = False, sort: 'bool' = True, ascending: 'bool' = False, bins=None, dropna: 'bool' = False) -> 'Series'
1.0 6
NaN 4
dtype: int64
Obviously, it works with pd.value_counts
too:
pd.value_counts.__defaults__ = (False, True, False, None, False)
pd.value_counts(sr)
Output:
1.0 6
NaN 4
dtype: int64