英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论