更改整个 Jupyter 笔记本的 Pandas 方法默认参数。

huangapple go评论48阅读模式
英文:

change pandas method default parameter for whole jupyter notebook

问题

有没有办法在Jupyter笔记本中更改pandas.value_counts(dropna=False)方法的默认参数,以便在调用它的所有情况下都生效?

我已经尝试使用包装函数,但更喜欢默认方法。

def my_value_counts(series, dropna=False, *args, **kwargs):
    return series.value_counts(dropna=dropna, *args, **kwargs)
英文:

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)

答案1

得分: 2

在Python中,即使对于现有的实例,你也可以更改函数或方法的默认签名:

import pandas as pd
import numpy as np
import inspect

sr = pd.Series(np.random.choice([1, np.nan], 10))

# 默认行为
print(inspect.signature(sr.value_counts))
print(sr.value_counts())

# 这是诀窍
pd.Series.value_counts.__defaults__ = (False, True, False, None, False)

# 新行为
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
英文:

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

huangapple
  • 本文由 发表于 2023年6月8日 02:25:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定