我正在尝试使用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)
Run Code Online (Sandbox Code Playgroud)
在手册中: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函数和一个使用多个参数的函数.
我只想简要说明一下张晓臣的回答,以防对某人有帮助。让我们举一个例子,我们想用特定的问候来问候一列人。
def greet(name, greeting):
print(f'{greeting}, {name}!')
names = np.array(["Luke", "Leia"]).reshape(2,1)
Run Code Online (Sandbox Code Playgroud)
由于apply_along_axisaccepts *args,我们可以将任意数量的参数传递给它,在这种情况下,每个参数都会传递给func1d。
为了避免 aSyntaxError: positional argument follows keyword argument我们必须标记参数:
np.apply_along_axis(func1d=greet, axis=1, arr=names, greeting='Hello')
Run Code Online (Sandbox Code Playgroud)
如果我们还有一个接受更多参数的函数
def greet_with_date(name, greeting, date):
print(f'{greeting}, {name}! Today is {date}.')
Run Code Online (Sandbox Code Playgroud)
我们可以通过以下任一方式使用它:
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')
Run Code Online (Sandbox Code Playgroud)
请注意,我们不需要担心关键字参数的顺序。
在*args中的签名numpy.apply_along_axis(func1d, axis, arr, *args)意味着有一些其他的位置参数可以通过.
如果要按元素添加两个numpy数组,只需使用+运算符:
In [112]: test_array = np.arange(10)
...: test_array2 = np.arange(10)
In [113]: test_array+test_array2
Out[113]: array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
Run Code Online (Sandbox Code Playgroud)
删除的关键字axis=,arr=,args=也应努力:
In [120]: np.apply_along_axis(example_func, 0, test_array, test_array2)
Out[120]: array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9265 次 |
| 最近记录: |