简体   繁体   English

numpy ndarray切片和迭代

[英]numpy ndarray slicing and iteration

I'm trying to slice and iterate over a multidimensional array at the same time. 我试图同时切片和遍历多维数组。 I have a solution that's functional, but it's kind of ugly, and I bet there's a slick way to do the iteration and slicing that I don't know about. 我有一个功能正常的解决方案,但它有点丑陋,我敢打赌,有一种精巧的方法可以执行我不知道的迭代和切片。 Here's the code: 这是代码:

import numpy as np
x = np.arange(64).reshape(4,4,4)
y = [x[i:i+2,j:j+2,k:k+2] for i in range(0,4,2) 
                          for j in range(0,4,2) 
                          for k in range(0,4,2)]
y = np.array(y)
z = np.array([np.min(u) for u in y]).reshape(y.shape[1:])

Your last reshape doesn't work, because y has no shape defined. 您的最后一次重塑无效,因为y没有定义任何形状。 Without it you get: 没有它,您将得到:

>>> x = np.arange(64).reshape(4,4,4)
>>> y = [x[i:i+2,j:j+2,k:k+2] for i in range(0,4,2) 
...                           for j in range(0,4,2) 
...                           for k in range(0,4,2)]
>>> z = np.array([np.min(u) for u in y])
>>> z
array([ 0,  2,  8, 10, 32, 34, 40, 42])

But despite that, what you probably want is reshaping your array to 6 dimensions, which gets you the same result as above: 但是尽管如此,您可能想要将数组重塑为6维,这将获得与上述相同的结果:

>>> xx = x.reshape(2, 2, 2, 2, 2, 2)
>>> zz = xx.min(axis=-1).min(axis=-2).min(axis=-3)
>>> zz
array([[[ 0,  2],
        [ 8, 10]],

       [[32, 34],
        [40, 42]]])
>>> zz.ravel()
array([ 0,  2,  8, 10, 32, 34, 40, 42])

It's hard to tell exactly what you want in the last mean, but you can use stride_tricks to get a "slicker" way. 很难准确地说出您到底想要什么,但是您可以使用stride_tricks来获得“流畅”的效果。 It's rather tricky. 这很棘手。

import numpy.lib.stride_tricks

# This returns a view with custom strides, x2[i,j,k] matches y[4*i+2*j+k]
x2 = numpy.lib.stride_tricks(
        x, shape=(2,2,2,2,2,2),
        strides=(numpy.array([32,8,2,16,4,1])*x.dtype.itemsize))

z2 = z2.min(axis=-1).min(axis=-2).min(axis=-3)

Still, I can't say this is much more readable. 不过,我不能说这更具可读性。 (Or efficient, as each min call will make temporaries.) (或有效,因为每分钟打一次电话都会产生临时性。)

Note, my answer differs from Jaime's because I tried to match your elements of y. 注意,我的答案与Jaime的答案不同,因为我试图匹配您的y元素。 You can tell if you replace the min with max . 您可以判断是否将min替换为max

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

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