更改整个jupyter notebook的pandas方法默认参数

cvxl0en2  于 2023-06-20  发布在  其他
关注(0)|答案(1)|浏览(89)

有没有一种方法可以在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)
dzjeubhm

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.__defaults__ = (False, True, False, None, False)
pd.value_counts(sr)

输出:

1.0    6
NaN    4
dtype: int64

相关问题