简体   繁体   English

numpy中的3d数组访问

[英]3d array access in numpy

I have NxMx3 numpy array and want to get access to subarrays of size 3. For example I want instead of 我有NxMx3 numpy数组,想访问大小为3的子数组。例如,我想要代替

arr = [[[...]]]
for i in range(N):
    for j in range(M):
        b = do_something(arr[i][j])

write

map(lambda x: do_something(x), ???) # x - is array of size 3

How can I do this? 我怎样才能做到这一点?

The function do_something takes arrays of size 3 and returns a scalar, and I want to get the array of the results by applying the function to each length-3 subarray of my input. 函数do_something采用大小为3的数组并返回一个标量,我想通过将函数应用于输入的每个length-3子数组来获取结果数组。

If possible, you should manually vectorize your original function, because making use of vectorized arithmetic would be the most efficient solution. 如果可能的话,应该手动向量化原始函数,因为使用向量化算术将是最有效的解决方案。

If you don't want to or can't do that, you can use numpy.vectorize to use your function that works along a single dimension and generalize it to higher-dimensional arrays. 如果您不想这样做,可以使用numpy.vectorize来使用沿单一维度工作的函数,并将其推广到更高维度的数组。 it probably won't be faster than looping manually ( vectorize is essentially a wrapper for a for loop), but at least it will give you a more straightforward interface to calling your function. 它可能不会比手动循环要快( vectorize本质上是for循环的包装器),但是至少它会为您提供一个更直接的接口来调用函数。

Example: 例:

import numpy as np

def foo(x):
    ''''sum three numbers from input'''
    return x[0]+x[1]+x[2] # otherwise x.sum(), of course

foo_vector = np.vectorize(foo,signature='(n)->()')

# try with dummy input
arr = np.random.rand(2,4,3)
#print(foo(arr)) # leads to an error
print(foo_vector(arr).shape)
# (2, 4)
print(np.allclose(foo_vector(arr),arr.sum(axis=-1)))
# True

As you can see from the above, vectorize handles additional leading dimensions of your array, and applies your function appropriately. 从上面可以看到, vectorize处理数组的其他前导维,并适当地应用函数。 Since you exactly want to apply your function along the last dimension, this should work like a charm, and applying foo_vector to an array of shape (M,N,3) should return an array of shape (M,N) with the result. 由于您foo_vector想沿最后一个维度应用函数,因此这应该像魅力一样工作,并且将foo_vector应用于形状(M,N,3)的数组应返回形状(M,N)的数组,并带有结果。

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

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