Numpy 数组遍历

NumPy 迭代器对象 numpy.nditer提供了一种灵活访问一个或者多个数组元素的方式。

迭代器最基本的任务的可以完成对数组元素的访问。

import numpy as np

a = np.arange(6).reshape(2,3)
print ('原始数组是:')
print (a)
print ('\n')
print ('迭代输出元素:')
for x in np.nditer(a):
    print (x, end=", " )
print ('\n')

原始数组是:
[[0 1 2]
 [3 4 5]]


迭代输出元素:
0, 1, 2, 3, 4, 5,

以上实例不是使用标准 C 或者 Fortran 顺序,选择的顺序是和数组内存布局一致的,这样做是为了提升访问的效率,默认是行序优先(row-major order,或者说是 C-order)。

控制遍历顺序

  • for x in np.nditer(a, order='F'):Fortran order,即是列序优先;
  • for x in np.nditer(a.T, order='C'):C order,即是行序优先;
import numpy as np

a = np.arange(0,60,5) 
a = a.reshape(3,4)  
print ('原始数组是:') 
print (a) 
原始数组是:
[[ 0  5 10 15]
 [20 25 30 35]
 [40 45 50 55]]


print ('\n') 
print ('原始数组的转置是:') 
b = a.T 
print (b) 
原始数组的转置是:
[[ 0 20 40]
 [ 5 25 45]
 [10 30 50]
 [15 35 55]]



print ('\n') 
print ('以 C 风格顺序排序:') 
c = b.copy(order='C')  
print (c)
for x in np.nditer(c):  
    print (x, end=", " )

以 C 风格顺序排序:
[[ 0 20 40]
 [ 5 25 45]
 [10 30 50]
 [15 35 55]]
0, 20, 40, 5, 25, 45, 10, 30, 50, 15, 35, 55, 

print  ('\n') 
print  ('以 F 风格顺序排序:')
c = b.copy(order='F')  
print (c)
for x in np.nditer(c):  
    print (x, end=", " )

以 F 风格顺序排序:
[[ 0 20 40]
 [ 5 25 45]
 [10 30 50]
 [15 35 55]]
0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55,

可以通过显式设置,来强制 nditer 对象使用某种顺序:


import numpy as np 

a = np.arange(0,60,5) 
a = a.reshape(3,4)  
print ('原始数组是:')
print (a)
print ('\n')
print ('以 C 风格顺序排序:')
for x in np.nditer(a, order =  'C'):  
    print (x, end=", " )
print ('\n')
print ('以 F 风格顺序排序:')
for x in np.nditer(a, order =  'F'):  
    print (x, end=", " )
Update time: 2020-05-25

results matching ""

    No results matching ""