[英]Can I pass arbitrary keyword argument into a function?
I am writing a generic function to plot univariate distributions:我正在编写一个通用的 function 到 plot 单变量分布:
univariate_subplot_params = {"nrows": 7, "ncols": 2, "figsize": (12, 24), "dpi": 80}
univariate_histplot_params = {"kde": True, "hue": config.target_col,
"legend": False, "palette": {1: config.colors[0], 0: config.colors[3]}}
univariate_fig_params = {"suptitle": "Coronary"}
def plot_univariate(df: pd.DataFrame, predictors: str, univariate_subplot_params: Dict[str, Any],
univariate_histplot_params: Dict[str, Any],
univariate_fig_params: Dict[str, Any]) -> None:
"""
Take in continuous predictors and plot univariate distribution.
Note in this setting, we have kde=True.
Args:
df (pd.DataFrame): Dataframe.
predictor (str): Predictor name.
"""
fig, axs = plt.subplots(**univariate_subplot_params)
for i, col in enumerate(predictors):
sns.histplot(
data=df,
x=col,
ax=axs[i % univariate_subplot_params["nrows"]][i // univariate_subplot_params["nrows"]],
**univariate_histplot_params)
plt.subplots_adjust(hspace=2)
fig.suptitle(
univariate_fig_params.get("suptitle", ""), y=1.01, fontsize="x-large"
)
fig.legend(df[config.target_col].unique())
fig.tight_layout()
plt.show()
And in matplotlib
or any plotting libraries, there are many many *args
inside.而在matplotlib
或任何绘图库中,里面有很多很多*args
。 I would like to define the configuration for them so I can pass it in like the code above.我想为它们定义配置,这样我就可以像上面的代码一样将其传入。
I am thinking if I can do the following:我正在考虑是否可以执行以下操作:
def plot_univariate(df: pd.DataFrame, predictors: str, *args) -> None:
"""
Take in continuous predictors and plot univariate distribution.
Note in this setting, we have kde=True.
Args:
df (pd.DataFrame): Dataframe.
predictor (str): Predictor name.
"""
fig, axs = plt.subplots(USE_ARGS)
for i, col in enumerate(predictors):
sns.histplot(
data=df,
x=col,
USE_ARGS)
plt.subplots_adjust(hspace=2)
fig.suptitle(
TITLE=USE_ARGS, y=1.01, fontsize="x-large"
)
fig.legend(df[config.target_col].unique())
fig.tight_layout()
plt.show()
Where I am able to pass in any arguments instead of pre-defined dictionaries?我可以在哪里传递任何 arguments 而不是预定义的字典?
Arbitrary keyword arguments (conventionally known as kwargs) are an essential part of Python.任意关键字 arguments(通常称为 kwargs)是 Python 的重要组成部分。
Here's an example (note the syntax):这是一个示例(注意语法):
def func(**kwargs):
print(kwargs)
func(a=1, b=2)
Output: Output:
{'a': 1, 'b': 2}
As you can see, what actually gets passed is a reference to a dictionary containing the argument names (keys) and their associated values如您所见,实际传递的是对包含参数名称(键)及其关联值的字典的引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.