如何初始化数组numpy的为每列不同的默认值? [英] How to initialize NumPy array with different default value for each column?
问题描述
我想初始化大小(x,y),其中y是非常大的numpy的矩阵。
I'm trying to initialize a NumPy matrix of size (x,y) where y is very large.
矩阵的第一列是一个ID(整数),其余的是三胞胎(int8的),其中,三重峰中的每个成员应该有不同的默认值。
The first column of the matrix is an ID (integer), and the rest are triplets (int8), where each member of the triplet should have a different default value.
即。假设默认值 [2,5,9]
我想初始化以下矩阵:
i.e. assuming the default values are [2,5,9]
I'd like to initialize the following matrix:
0 2 5 9 2 5 9 2 5 9 ...
0 2 5 9 2 5 9 2 5 9 ...
0 2 5 9 2 5 9 2 5 9 ...
0 2 5 9 2 5 9 2 5 9 ...
...
我能想到初始化矩阵的最快方法是:
The fastest way I could think of initializing the matrix is:
defaults = [2, 5, 9]
mat = numpy.zeros(shape=(x,y),
dtype=['i'] + ['int8'] * (y - 1))
# fill the triplets with default values
for i in range(1, y/3):
j = i * 3
mat[:, j] = defaults[0]
mat[:, j+1] = defaults[1]
mat[:, j+2] = defaults[2]
什么是初始化这样一个矩阵的最快方法?
What is the fastest way to initialize such a matrix?
谢谢!
推荐答案
您可以使用 np.tile
与重塑值阵列,例如:
You can use np.tile
with reshaping the value array,for example :
>>> b=np.array([2,5,9])
>>> b=b.reshape(3,1)
>>> np.tile(b,3)
array([[2, 2, 2],
[5, 5, 5],
[9, 9, 9]])
然后你可以使用 np.dstack
旋转阵列,然后使用 np.hstack
添加零列
Then you can use np.dstack
to rotate the array then use np.hstack
to add the zeros columns :
>>> np.hstack((np.zeros((3,1)),np.dstack(new)[0]))
array([[ 0., 2., 5., 9.],
[ 0., 2., 5., 9.],
[ 0., 2., 5., 9.]])
或者你可以再次重复无零的部分瓷砖
:
Or you can repeat the none zero part again with tile
:
>>> np.hstack((np.zeros((3,1)),np.tile(np.dstack(new)[0],4)))
array([[ 0., 2., 5., 9., 2., 5., 9., 2., 5., 9., 2., 5., 9.],
[ 0., 2., 5., 9., 2., 5., 9., 2., 5., 9., 2., 5., 9.],
[ 0., 2., 5., 9., 2., 5., 9., 2., 5., 9., 2., 5., 9.]])
编辑:
只是为了澄清,简单的单行是这样的:
Just for clarification, the simple one liner is this:
defaults = [2, 5, 9]
np.hstack((np.zeros((x,1)), np.tile(defaults, (x,y))))
这篇关于如何初始化数组numpy的为每列不同的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!