比如我想要這樣的矩陣:
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
不行,因?yàn)樗荒苡靡粋€ scalar 填充矩陣,不能用 [123, 3, 21]
填充。
此外我還想給某矩陣「加若干維」:
In [11]: a = np.arange(10)
In [13]: b = np.asarray([a])
In [14]: b
Out[14]: array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
比如我想給現(xiàn)成的 a
加一維,只能如此手動包裝 np.asarray([a])
, 不知 Numpy 有什么 numpy.squeeze
的「反函數(shù)」可以拿來用。
光陰似箭催人老,日月如移越少年。
For the first question, just refer to the one above. For the second extended latitude, numpy has a special function: 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]])
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]])