python - 在 Numpy 里如何高效地定制矩陣?
問題描述
比如我想要這樣的矩陣:
In [10]: np.array([[(123, 3, 21)] * 3] * 2)Out[10]: array([[[123, 3, 21],[123, 3, 21],[123, 3, 21]], [[123, 3, 21],[123, 3, 21],[123, 3, 21]]])
Numpy 里有什么辦法能代替如此粗魯?shù)摹噶斜沓朔ā??顯然 numpy.full 不行,因為它只能用一個 scalar 填充矩陣,不能用 [123, 3, 21] 填充。
此外我還想給某矩陣「加若干維」:
In [11]: a = np.arange(10)In [13]: b = np.asarray([a])In [14]: bOut[14]: array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
比如我想給現(xiàn)成的 a 加一維,只能如此手動包裝 np.asarray([a]), 不知 Numpy 有什么 numpy.squeeze 的「反函數(shù)」可以拿來用。
問題解答
回答1:第一個問題,參考樓上的就好,第二個擴(kuò)展緯度,numpy有專門的函數(shù): expand_dims
In [1] import numpy as np In [2] a = np.arange(10) In [3] b = np.expand_dims(a, axis=0) # axis表示在那一維(軸)插入新的維度 In [4] b Out[4] array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])回答2:
np.tile((123, 3, 21), (2, 3, 1))
?In?[1]?? import numpy as np?In?[2]?? a = np.arange(10)?In?[3]?? b = a.reshape((1, 10))?In?[4]?? b?Out[4]?? array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
相關(guān)文章:
1. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。2. 關(guān)于docker下的nginx壓力測試3. angular.js - angularjs的自定義過濾器如何給文字加顏色?4. docker-machine添加一個已有的docker主機(jī)問題5. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.6. 為什么我ping不通我的docker容器呢???7. docker - 如何修改運行中容器的配置8. nignx - docker內(nèi)nginx 80端口被占用9. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題10. docker鏡像push報錯
