有没有一种方法可以在Jupyter notebook中更改pandas. value_counts(dropna = False)方法的默认参数,以适应它被调用的所有情况?我曾尝试使用 Package 函数,但更愿意使用默认方法
def my_value_counts(series, dropna=False, *args, **kwargs): return series.value_counts(dropna=dropna, *args, **kwargs)
dzjeubhm1#
在python中,你可以更改函数或方法的默认签名,即使是现有示例:
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())
输出:
(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
显然,它也适用于pd.value_counts:
pd.value_counts
pd.value_counts.__defaults__ = (False, True, False, None, False) pd.value_counts(sr)
1.0 6 NaN 4 dtype: int64
1条答案
按热度按时间dzjeubhm1#
在python中,你可以更改函数或方法的默认签名,即使是现有示例:
输出:
显然,它也适用于
pd.value_counts
:输出: