Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

在 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 里有什么办法能代替如此粗鲁的「列表乘法」?显然 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 的「反函数」可以拿来用。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

第一个问题,参考楼上的就好,第二个扩展纬度,numpy有专门的函数: 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]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...