當前位置:
首頁 >
python3-numpy np.nditer 迭代数组、np.nditer修改数组、np.nditer广播迭代
發布時間:2024/9/27
30
豆豆
生活随笔
收集整理的這篇文章主要介紹了
python3-numpy np.nditer 迭代数组、np.nditer修改数组、np.nditer广播迭代
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、基本使用
import numpy as np""" NumPy 迭代器對象 numpy.nditer 提供了一種靈活訪問一個或者多個數組元素的方式。 迭代器最基本的任務的可以完成對數組元素的訪問。 """ a = np.arange(6).reshape(2,3) print ('原始數組是:') print (a) 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)。 """ # 我們可以通過迭代上述數組的轉置來看到這一點,并與以 C 順序訪問數組轉置的 copy 方式做對比,如下實例: a = np.arange(6).reshape(2, 3) for x in np.nditer(a.T):print(x, end=", ") # 0, 1, 2, 3, 4, 5, print('\n')for x in np.nditer(a.T.copy(order='C')):print(x, end=", ") # 0, 3, 1, 4, 2, 5, print('\n')print(a.T) print(a.T.copy(order='C')) """ [[0 3][1 4][2 5]] [[0 3][1 4][2 5]]從上述例子可以看出,a 和 a.T 的遍歷順序是一樣的,也就是他們在內存中的存儲順序也是一樣的,但是 a.T.copy(order = 'C') 的遍歷結果是不同的,那是因為它和前兩種的存儲方式是不一樣的,默認是按行訪問。 """2、控制遍歷順序
for x in np.nditer(a, order=‘F’):Fortran order,即是列序優先;
for x in np.nditer(a.T, order=‘C’):C order,即是行序優先;
方式一、使用copy
方式二、顯式設置,強制 nditer 對象使用某種順序
# 可以通過顯式設置,來強制 nditer 對象使用某種順序: a = np.arange(0,60,5) a = a.reshape(3,4) print ('原始數組是:') print (a) 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=", " )""" 原始數組是: [[ 0 5 10 15][20 25 30 35][40 45 50 55]] 以 C 風格順序排序: 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 以 F 風格順序排序: 0, 20, 40, 5, 25, 45, 10, 30, 50, 15, 35, 55, """3、修改數組中元素的值
nditer 對象有另一個可選參數 op_flags。 默認情況下,nditer 將視待迭代遍歷的數組為只讀對象(read-only),為了在遍歷數組的同時,實現對數組元素值得修改,必須指定 read-write 或者 write-only 的模式。
a = np.arange(0,60,5) a = a.reshape(3,4) print ('原始數組是:') print (a) print ('\n') for x in np.nditer(a, op_flags=['readwrite']):x[...]=2*x print ('修改后的數組是:') print (a) """ 原始數組是: [[ 0 5 10 15][20 25 30 35][40 45 50 55]] 修改后的數組是: [[ 0 10 20 30][ 40 50 60 70][ 80 90 100 110]] """4、廣播迭代
如果兩個數組是可廣播的,nditer 組合對象能夠同時迭代它們。 假設數組 a 的維度為 3X4,數組 b 的維度為 1X4 ,則使用以下迭代器(數組 b 被廣播到 a 的大小)。
a = np.arange(0,60,5) a = a.reshape(3,4) print ('第一個數組為:') print (a) print ('\n') print ('第二個數組為:') b = np.array([1, 2, 3, 4], dtype = int) print (b) print ('\n') print ('修改后的數組為:') for x,y in np.nditer([a,b]):print ("%d:%d" % (x,y), end=", " ) """第一個數組為: [[ 0 5 10 15][20 25 30 35][40 45 50 55]] 第二個數組為: [1 2 3 4] 修改后的數組為: 0:1, 5:2, 10:3, 15:4, 20:1, 25:2, 30:3, 35:4, 40:1, 45:2, 50:3, 55:4, """https://www.runoob.com/numpy/numpy-terating-over-array.html
總結
以上是生活随笔為你收集整理的python3-numpy np.nditer 迭代数组、np.nditer修改数组、np.nditer广播迭代的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 只需要4步即可在vue2中使用路由rou
- 下一篇: mybatis resultMap ty