gpt4 book ai didi

python - Numpy apply_along_axis 函数

转载 作者:太空狗 更新时间:2023-10-29 22:26:29 27 4
gpt4 key购买 nike

我正在尝试将 numpys apply_along_axis 与需要多个参数的函数一起使用。

test_array = np.arange(10)
test_array2 = np.arange(10)

def example_func(a,b):
return a+b

np.apply_along_axis(example_func, axis=0, arr=test_array, args=test_array2)

在手册中:http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html有附加参数的参数 args 。但是,如果我尝试添加该参数,python 会返回错误:

*TypeError: apply_along_axis() 得到了一个意外的关键字参数 'args'*

或者如果我不使用 args 则缺少参数

*TypeError: example_func() 恰好接受 2 个参数(给定 1 个)*

这只是一个示例代码,我知道我可以用不同的方式解决这个问题,比如使用 numpy.add 或 np.vectorize。但我的问题是我是否可以将 numpys apply_along_axis 函数与使用多个参数的函数一起使用。

最佳答案

我只想简单阐述一下zhangxaochen's answer ,以防万一。让我们举一个例子,我们想用特定的问候语来问候一列人。

def greet(name, greeting):
print(f'{greeting}, {name}!')

names = np.array(["Luke", "Leia"]).reshape(2,1)

由于apply_along_axis接受*args,我们可以pass an arbitrary number of arguments to it ,在这种情况下,它们将分别传递给 func1d

避免语法错误

为了避免 SyntaxError: positional argument follows keyword argument 我们必须标记参数:

np.apply_along_axis(func1d=greet, axis=1, arr=names, greeting='Hello')

不止一个附加参数

如果我们还有一个接受更多参数的函数

def greet_with_date(name, greeting, date):
print(f'{greeting}, {name}! Today is {date}.')

我们可以通过以下任一方式使用它:

np.apply_along_axis(greet_with_date, 1, names, 'Hello', 'May 4th')
np.apply_along_axis(func1d=greet_with_date, axis=1, arr=names, date='May 4th', greeting='Hello')

请注意,我们无需担心关键字参数的顺序。

关于python - Numpy apply_along_axis 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com