函数及其参数的功能

数据挖掘 Python
2022-03-09 20:59:16

我想建立一个熊猫随机数据框。为了实现这个目的,我需要一个 Python 函数作为参数:

  • numpy 分布
  • 他们的论点。

例如 :

分布1:正常| 参数:手段 = 0 ,标准开发 = 1 ,大小 = 100

分布2:均匀| 参数:低 = 0,高 = 1,大小 = 100

ETC...

我事先不知道不同的分布及其论点会是什么。

然后,主函数将使用每个相应的参数生成分布的随机样本。

我尝试过类似的东西:

import numpy as np

def myfun( **kwargs ) :
    for k , v in kwargs.items() :
        print( k )
        print( v )

当我使用这些参数调用该函数时:

myfun( fun_1 = 'np.random.normal' , arg_1 = { 'loc' : 0 , 'scale' : 1 , 'size' : 7 } ,
       fun_2 = 'np.random.uniform' , arg_2 = { 'low' : 0 , 'high' : 1 , 'size' : 7 } )

输出是:

fun_1
np.random.normal
arg_1
{'loc': 0, 'scale': 1, 'size': 7}
fun_2
np.random.uniform
arg_2
{'low': 0, 'high': 1, 'size': 7}

但我的目的不是打印所需的分布及其相关参数,而是为每个分布生成一个样本。

1个回答

我假设你知道一旦你进入你的函数,哪些分布是可能的?我可能只是传递一个分布名称的参数,然后是 Python 字典中的一组参数。

此方法还允许非常简单的测试,因为您知道分布只需要某些参数,因此您还可以添加小检查以确认一切可用。

def my_distribution(dist_name, dist_params):
    if dist_name == "normal":
        assert ("mean" in params.keys()) and ("variance" in params.keys()), "Missing expected parameters for {} distribution".format(dist_name)
    # Perform some checks for other distributions as necessary...

    # perform your own steps...

现在你像这样使用它:

# assume these are provided by your earlier code
distr = "normal"
params = {"mean": 5.0, "variance": 2.0}

result = my_distribution(dist_name=distr, dist_params=params)

编辑:

这是一个可以在单个调用中处理多个分布的单个函数的示例:

def my_distributions(dist_collection):
    # Perform some checks for other distributions as necessary...
    allowed_dists = ["normal", "uniform", "dirichlet", "rayleigh"]
    assert all(
        dist_name in allowed_dists for dist_name in dist_collection
    ), "Input contains disallowed distribution"

    # Do something for each distribution name with its parameters:
    for dist_name, dist_params in params.items():
        print(dist_name, dist_params)

现在需要稍微不同地指定输入:

all_distributions = {
    "normal": {"loc": 1, "scale": 2, "size": 100},
    "uniform": {"low": 0, "high": 1, "size": 100},
}

一个调用现在可以在多个发行版上工作:

my_distributions(all_distributions)

您当然可以创建包含所有配置和检查的类,但我认为您开始使事情变得不必要地复杂,因为 Numpy 已经通过其内置的分发功能为您做了很多事情。