简体   繁体   English

将函数应用于np.ndarray?

[英]apply a function to np.ndarray?

I have one numpy array, for instance a (a.shape = (2,20,50,50)). 我有一个numpy数组,例如一个(a.shape =(2,20,50,50))。 I would like to apply a function over its second axes. 我想在第二个轴上应用一个函数。

My function is the difference between each elements only along the second axis, ie 我的功能是仅沿第二个轴的每个元素之间的差异,即

res = a[:,i+1,:,:] - a[:,i,:,:] for i in range(20)

I have already tried it with lambda function, but the output is a list. 我已经用lambda函数尝试过了,但是输出是一个列表。 I would like to have the result with the same shape as a. 我希望得到与a形状相同的结果。 That means I want to have res.shape = (2,20,50,50). 这意味着我想拥有res.shape =(2,20,50,50)。

I do appreciate that if someone guide me. 我真的很感谢有人指导我。

Thank you in advance. 先感谢您。

You don't need to apply a function. 您不需要应用功能。 Just subtract them directly. 只需直接减去它们。

res = a[:,1:,:,:]-a[:,0:-1,:,:]

Moreover, you won't get (2,20,50,50) ndarray but (2,19,50,50). 此外,您不会得到(2,20,50,50)ndarray,而会得到(2,19,50,50)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM