[英]combining vectors as column matrix in numpy
I have 3 vectors like the following: 我有以下三个向量:
a = np.ones(20)
b = np.zeros(20)
c = np.ones(20)
I am trying to combine them into one matrix of dimension 20x3. 我正在尝试将它们合并为20x3尺寸的矩阵。
Currently I am doing: 目前我正在做:
n1 = np.vstack((a,b))
n2 = np.vstack((n1,c)).T
This works, but isn't there a way to fill matrix with arrays in column-wise fashion? 这可行,但是没有办法以列方式用数组填充矩阵吗?
There are a few different ways you could do this. 您可以通过几种不同的方法来执行此操作。 Here are a some examples: 以下是一些示例:
np.c_[a, b, c]
Using np.dstack
and np.squeeze
: 使用np.dstack
和np.squeeze
:
np.dstack((a, b, c)).squeeze()
Using np.vstack
and transpose (similar to your method): 使用np.vstack
和转置(类似于您的方法):
np.vstack((a,b,c)).T
Using np.concatenate
and reshape
: 使用np.concatenate
和reshape
:
np.concatenate((a, b, c)).reshape((-1, 3), order='F')
If efficiency matters here, the last method using np.concatenate
appears to be by far the quickest on my computer: 如果效率很重要,那么使用np.concatenate
的最后一种方法似乎是我计算机上最快的方法:
>>> %timeit np.c_[a, b, c]
10000 loops, best of 3: 46.7 us per loop
>>> %timeit np.dstack((a, b, c)).squeeze()
100000 loops, best of 3: 18.2 us per loop
>>> %timeit np.vstack((a,b,c)).T
100000 loops, best of 3: 17.8 us per loop
>>> %timeit np.concatenate((a, b, c)).reshape((-1, 3), order='F')
100000 loops, best of 3: 3.41 us per loop
Yes, use column_stack
: 是的,使用column_stack
:
np.column_stack((a,b,c))
That works for stacking general 1-d arrays. 这适用于堆叠通用的一维数组。 In your specific case where you want a 20x3
array such that each row is (1,0,1)
, I'd suggest: 在您想要20x3
数组,使得每一行为(1,0,1)
的特定情况下,我建议:
np.tile([1.,0.,1.], (20,1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.