numpy.reshape()的函數(shù)的具體使用
np.reshape()基本用法
常用于矩陣規(guī)格變換,將矩陣轉(zhuǎn)換為特定的行和列的矩陣
格式:a1.reshape(x,y,z,…)
注意:將矩陣a1轉(zhuǎn)變成(x, y,z,…)---->一維長度x,二維長度y,三維長度z,…的矩陣。
場景:matlibplot畫圖時(shí)x、y軸需要傳入的是一維,可以用reshape()實(shí)現(xiàn);再例如需要將多維的變成行向量或列向量時(shí)也經(jīng)常要用
numpy.reshape(a, newshape, order='C')[source],參數(shù)`newshape`是啥意思?
根據(jù)Numpy文檔(https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy-reshape)的解釋:
newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, **the value is inferred from the length of the array and remaining dimensions**.
大意是說,數(shù)組新的shape屬性應(yīng)該要與原來的配套,如果等于-1的話,那么Numpy會(huì)根據(jù)剩下的維度計(jì)算出數(shù)組的另外一個(gè)shape屬性值。
舉幾個(gè)例子或許就清楚了,有一個(gè)數(shù)組z,它的shape屬性是(4, 4)
z = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
z.shape
(4, 4)
z.reshape(-1)
z.reshape(-1) array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
z.reshape(-1, 1)
也就是說,先前我們不知道z的shape屬性是多少,但是想讓z變成只有一列,行數(shù)不知道多少,通過`z.reshape(-1,1)`,Numpy自動(dòng)計(jì)算出有12行,新的數(shù)組shape屬性為(16, 1),與原來的(4, 4)配套。
z.reshape(-1,1)
array([[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12],
[13],
[14],
[15],
[16]])
z.reshape(-1, 2)
newshape等于-1,列數(shù)等于2,行數(shù)未知,reshape后的shape等于(8, 2)
z.reshape(-1, 2)
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12],
[13, 14],
[15, 16]])
同理,只給定行數(shù),newshape等于-1,Numpy也可以自動(dòng)計(jì)算出新數(shù)組的列數(shù)。
到此這篇關(guān)于numpy.reshape()的函數(shù)的具體使用的文章就介紹到這了,更多相關(guān)numpy.reshape()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python開發(fā)游戲之井字游戲的實(shí)戰(zhàn)步驟
最近正在學(xué)習(xí)Python,所以最近做了一個(gè)關(guān)于Python的實(shí)例,下面這篇文章主要給大家介紹了關(guān)于Python開發(fā)游戲之井字游戲的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
Python腳本實(shí)現(xiàn)DNSPod DNS動(dòng)態(tài)解析域名
這篇文章主要介紹了Python腳本實(shí)現(xiàn)DNSPod DNS動(dòng)態(tài)解析域名,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-02-02
三大Python翻譯神器再也不用擔(dān)心學(xué)不好英語
本文介紹了用python做一款屬于自己的翻譯詞典軟件,從此告別網(wǎng)頁搜索,文中有非常詳細(xì)的代碼示例,小伙伴們快快行動(dòng)吧,需要的朋友可以參考下2021-09-09
Python反爬機(jī)制-驗(yàn)證碼功能的具體實(shí)現(xiàn)過程
Tesseract-OCR是一個(gè)免費(fèi)、開源的OCR引擎,通過該引擎可以識別圖片中的驗(yàn)證碼,這篇文章主要介紹了Python反爬機(jī)制-驗(yàn)證碼的示例代碼,需要的朋友可以參考下2022-02-02

