python散点图图例 - python画图标题
用nditer浅迭代 (2)
或者重塑你
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
的标志和文档以遍历其中的两个维度。 当nditer
允许访问基础的迭代机制时,通常不需要使用它 - 除非你正在做一些不寻常的事情,或者试图用cython
加速代码。
这是一个从nditer
对象的迭代获取2个值的例子。 op
列表中的每个数组都有一个值。 x
和z
都是()
形状的数组。
for x,z in np.nditer([y,y]):
print x,z
在http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html有关于使用nditer
的更多信息
这个文档页面有一个使用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
来做这个简单的迭代,但是值得吗?
在迭代numpy数组的第一个d轴时 ,我偶然发现了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
使用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
的主要部分,我得到:
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]
我有这样一个数组:
>>>y = np.random.randint(0, 255, (2,2,3))
>>>array([[[242, 14, 211],
[198, 7, 0]],
[[235, 60, 81],
[164, 64, 236]]])
我必须迭代每个三元素元素(不幸的是矢量化不会帮助我在这里...)。 所以我试了一下:
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
我很确定我正在犯一个非常明显的错误...任何人都可以帮我吗?
看起来你只是需要把它压平。 你可以使用itertools中的chain
运算符。
from itertools import chain
y = np.random.randint(0, 255, (2,2,3)
b = chain.from_iterable(y) # where b is a generator
列表(b)输出
[array([ 51, 119, 84]),
array([ 50, 110, 193]),
array([165, 157, 52]),
array([239, 119, 83])]