python - 在 Numpy 里如何高效地定制矩阵?
大家讲道理
大家讲道理 2017-04-18 10:26:33
0
2
640

比如我想要这样的矩阵:

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 里有什么办法能代替如此粗鲁的「列表乘法」?显然 numpy.full 不行,因为它只能用一个 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]])

比如我想给现成的 a 加一维,只能如此手动包装 np.asarray([a]), 不知 Numpy 有什么 numpy.squeeze 的「反函数」可以拿来用。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
PHPzhong

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]])
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!