這個單維(dim length = 1)
可以添加作爲形狀標準,原來的陣列形狀np.insert
,從而直接改變其形狀,像這樣 -
x.shape = np.insert(x.shape,axis,1)
那麼,我們不妨延長這一邀請一個以上的新的座標軸帶着幾分np.diff
和np.cumsum
伎倆,像這樣 -
insert_idx = (np.diff(np.append(0,axis))-1).cumsum()+1
x.shape = np.insert(x.shape,insert_idx,1)
個
樣品試驗 -
In [151]: def addNewAxisAt(x, axis):
...: insert_idx = (np.diff(np.append(0,axis))-1).cumsum()+1
...: x.shape = np.insert(x.shape,insert_idx,1)
...:
In [152]: A = np.random.rand(4,5)
In [153]: addNewAxisAt(A, axis=1)
In [154]: A.shape
Out[154]: (4, 1, 5)
In [155]: A = np.random.rand(5,6,8,9,4,2)
In [156]: addNewAxisAt(A, axis=5)
In [157]: A.shape
Out[157]: (5, 6, 8, 9, 4, 1, 2)
In [158]: A = np.random.rand(5,6,8,9,4,2,6,7)
In [159]: addNewAxisAt(A, axis=(1,3,4,6))
In [160]: A.shape
Out[160]: (5, 1, 6, 1, 1, 8, 1, 9, 4, 2, 6, 7)
哦,當然!很容易忘記,ndarray的形狀是一個可設置的屬性 – wim
還有'numpy.reshape',它可以以非變化的方式做到這一點。 – user2357112
@ user2357112是!通過使用由代碼中'np.insert'輸出的新形狀信息。 – Divakar