使用 nditer 进行浅层迭代

2024-05-07

我有这样一个数组:

>>>y = np.random.randint(0, 255, (2,2,3))
>>>array([[[242, 14, 211],
           [198,  7,   0]],

          [[235,  60,  81],
           [164,  64, 236]]])

我必须迭代每个triplet元素(不幸的是矢量化在这里对我没有帮助......)。所以我尝试:

for i, j in np.nditer(y):
print y[i, j],

希望我能得到这样的输出:

[242, 14, 211], [198, 7, 0], [235, 60, 81], [164, 64, 236],但没有运气!

我收到错误:

Traceback (most recent call last):

  File "<ipython-input-21-a336ef837a8a>", line 1, in <module>
    for i, j in np.nditer(y):    print y[i,j]

TypeError: iteration over a 0-d array

我很确定我犯了一个非常明显的错误...有人可以帮助我吗?


或者重塑y

for i in y.reshape(-1,3):
    print i

双重迭代也有效:

for x in y:
    for z in x:
        print z

Plain nditer迭代每个元素y (nditer不给你索引):

for i in np.nditer(y):
    print i   
    # wrong y[i]

您需要深入了解以下内容的标志和文档nditer迭代其维度的 2 个。尽管nditer提供对底层迭代机制的访问,您通常不需要使用它 - 除非您正在做一些不寻常的事情,或者尝试使用cython.


下面是一个从迭代中获取 2 个值的示例nditer目的。数组中的每个数组都有一个值op列表。两个都x and z are ()形状数组。

for x,z in np.nditer([y,y]):
    print x,z

关于使用还有更多nditer at http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html


该文档页面有一个使用的示例external_loop将数组分成子数组,而不是单独的。我可以用 3d 完成同样的任务y通过重新排序其轴:

y3=y.swapaxes(2,0).copy(order='C')
for i in np.nditer(y3,order='F',flags=['external_loop']):
    print i,

[242  14 211] [198   7   0] [235  60  81] [164  64 236]

所以我们可以使用nditer进行这种浅层迭代,但这值得吗?


In 迭代 numpy 数组的前 d 轴 https://stackoverflow.com/questions/25249380,我偶然发现ndindex:

for i in np.ndindex(y.shape[:2]):
    print y[i],
# [242  14 211] [198   7   0] [235  60  81] [164  64 236]

ndindex uses nditer。生成浅层迭代的技巧是使用仅使用要迭代的维度的子数组。

class ndindex(object):
    def __init__(self, *shape):
        ...
        x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape))
        self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'], order='C')
    def __next__(self):
        next(self._it)
        return self._it.multi_index

或者剥离掉重要的部分ndindex I get:

xx = np.zeros(y.shape[:2])
it = np.nditer(xx,flags=['multi_index'])                               
while not it.finished:
    print y[it.multi_index],
    it.iternext()
# [242  14 211] [198   7   0] [235  60  81] [164  64 236]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 nditer 进行浅层迭代 的相关文章

随机推荐