python運算學習之Numpy ------ 數組的切片索引與迴圈遍曆、條件和布爾數組、

來源:互聯網
上載者:User

標籤:0.11   遍曆   UNC   body   row   test   style   and   索引   

數組的切片索引:

  數組的切片索引和列表非常類似,下面用代碼簡單說明

 1 a = np.random.rand(16).reshape(4, 4) 2 print("數組a:\n", a) 3 print(a[-1][1:4]) 4 Out[1]: 5 數組a: 6  [[0.04175379 0.43013992 0.5398909  0.40638248] 7  [0.3305902  0.11958799 0.48680358 0.30755734] 8  [0.00893887 0.3848716  0.21018253 0.88170218] 9  [0.80198391 0.4922656  0.67535542 0.64647139]]10 [0.4922656  0.67535542 0.64647139]

  由於和列表類似,且要符號多維陣列的特徵,所以這裡不過多闡述。有需要參考列表的相關知識。

 

數組的迴圈遍曆:

 1 a = np.random.rand(9).reshape(3, 3) 2 print("數組a:\n", a) 3 for row in a: 4     print(row)  # 一行一行的輸出 5 for item in a.flat: 6     print(item) 7 # 通用的迴圈函數 8 for_test = np.apply_along_axis(np.mean, axis=0, arr=a)  # apply_along_axis(func1d, axis, arr, *args, **kwargs) 9 print("np.apply_along_axis的調試:\n", for_test)  # axis=0為按列,axis=1為按行10 Out[2]:11 數組a:12  [[0.97420758 0.20766438 0.52942127]13  [0.82673775 0.44288163 0.41729451]14  [0.1373707  0.68103565 0.92256133]]15 [0.97420758 0.20766438 0.52942127]16 [0.82673775 0.44288163 0.41729451]17 [0.1373707  0.68103565 0.92256133]18 0.974207580408193719 0.2076643828993124420 0.529421266587482921 0.826737745734586522 0.4428816319988966323 0.417294507990859324 0.1373707028041961725 0.681035645937522226 0.92256133122830327 np.apply_along_axis的調試:28  [0.64610534 0.44386055 0.62309237]

  np.apply_along_axis()方法在我們對矩陣按行按列操作的時候最好用它。注意,第一個參數是方法,方法可以是自己對矩陣每個元素操作的函數方法。

條件和布爾數組:

 
1 a = np.random.rand(9).reshape(3, 3)2 print(a < 0.5)          # 輸出布爾數組3 print(a[a < 0.5])       # 輸出true對應的元素4 Out[3]:5 [[ True False  True]6  [False  True False]7  [False  True False]]8 [0.19353844 0.03944841 0.38137674 0.3069755 ]

數組 形狀變化:

 1 a = np.random.rand(9).reshape(3, 3) 2 a = a.ravel()  # 此時的a是一個新數組 3 print(a)  # 將數組平鋪成一維數組 4 a.shape = (3, 3)  # 你也可以用reshape 5 print(a) 6 Out[4]: 7 [0.83017305 0.11660585 0.83060752 0.221212   0.35489551 0.74925696 8  0.61087204 0.85969402 0.90966368] 9 [[0.83017305 0.11660585 0.83060752]10  [0.221212   0.35489551 0.74925696]11  [0.61087204 0.85969402 0.90966368]]

  注意用A.T表示轉置,或者用A.transpose()。

 

python運算學習之Numpy ------ 數組的切片索引與迴圈遍曆、條件和布爾數組、

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.