NumPy迭代数组

numpy.nditer是NumPy的一个迭代器对象,提供能够灵活的访问一个或者多个属猪元素的方式。

# 迭代
z=np.arange(6).reshape(3,2)
for x in np.nditer(z):
    print(x,end=',')

运行结果:
0, 1, 2, 3, 4, 5,

以上利用nditer函数实现了一个迭代的过程。

下面来比较下z 、 z.T(转换成矩阵) 、z.T.copy(order='C') (order可以指定行或者列优先) 的迭代效果

# 迭代
z=np.arange(6).reshape(3,2)
for x in np.nditer(z):
    print(x,end=',')
print('
')
for x in np.nditer(z,order='C'):
    print(x,end=',')
print('
')
for x in np.nditer(z.T,order='C'):
    print(x,end=',')
print('
')
for x in np.nditer(z.T.copy(order='F')):
    print(x,end=',')
print('
')
for x in np.nditer(z.T.copy(order='C')):
    print(x,end=',')

运行结果:

0,1,2,3,4,5,

0,1,2,3,4,5,

0,2,4,1,3,5,

0,1,2,3,4,5,

0,2,4,1,3,5,
Process finished with exit code 0

nditer 对象有另一个可选参数 op_flags。 默认情况下,nditer 将视待迭代遍历的数组为只读对象(read-only),为了在遍历数组的同时,实现对数组元素值得修改,必须指定 read-write 或者 write-only 的模式。如设置x:     for x in np.nditer(a, op_flags=['readwrite']):

nditer类的构造器拥有flags参数,它可以接受下列值:

c_index :跟踪C的顺序索引

f_index 跟踪Fortran的顺序索引

multi-index :每次迭代可以跟踪一种索类型

external_loop: 给出的值是具有多个值的一维数组,而不是零数组。

# 改变迭代的值
az = np.arange(0,72,6)
az = az.reshape(3,4)
print (az)
for x in np.nditer(az,flags=['external_loop'],order='F'):
    print(x,end=',')

以上是flags=external_loop的运用,对比结果如下:

[[ 0  6 12 18]
 [24 30 36 42]
 [48 54 60 66]]
[ 0 24 48],[ 6 30 54],[12 36 60],[18 42 66],
Process finished with exit code 0

广播迭代

如果两个数组是可广播的,nditer 组合对象能够同时迭代它们。 假设数组 a 的维度为 3X4,数组 b 的维度为 1X4 ,则使用以下迭代器(数组 b 被广播到 a 的大小)。

 
# 广播迭代
a = np.arange(0,60,5)
a = a.reshape(3,4)
b = np.array([1,  2,  3,  4])
for x,y in np.nditer([a,b]):
    print ('%d 扩展 %d' % (x,y), end=", " )

运行结果:

0 扩展 1, 5 扩展 2, 10 扩展 3, 15 扩展 4, 20 扩展 1, 25 扩展 2, 30 扩展 3, 35 扩展 4, 40 扩展 1, 45 扩展 2, 50 扩展 3, 55 扩展 4, 
Process finished with exit code 0
原文地址:https://www.cnblogs.com/supershuai/p/12217731.html