将1D阵列合并为2D阵列 [英] Merging 1D arrays into a 2D array
问题描述
是否有一个内置函数将两个1D数组连接成2D数组? 考虑一个例子:
Is there a built-in function to join two 1D arrays into a 2D array? Consider an example:
X=np.array([1,2])
y=np.array([3,4])
result=np.array([[1,3],[2,4]])
我可以想到2个简单的解决方案. 第一个非常简单.
I can think of 2 simple solutions. The first one is pretty straightforward.
np.transpose([X,y])
另一个使用lambda函数.
The other one employs a lambda function.
np.array(list(map(lambda i: [a[i],b[i]], range(len(X)))))
尽管第二个看起来更复杂,但它的速度似乎几乎是第一个的两倍.
While the second one looks more complex, it seems to be almost twice as fast as the first one.
修改 第三种解决方案涉及zip()函数.
Edit A third solution involves the zip() function.
np.array(list(zip(X, y)))
它比lambda函数快,但比@Divakar建议的column_stack解决方案慢.
It's faster than the lambda function but slower than column_stack solution suggested by @Divakar.
np.column_stack((X,y))
推荐答案
请考虑可伸缩性.如果我们增加数组的大小,那么完整的numpy命令解决方案会更快:
Take into consideration scalability. If we increase the size of the arrays, fully numpy command solutions are quite faster:
np.random.seed(1234)
X = np.random.rand(10000)
y = np.random.rand(10000)
%timeit np.array(list(map(lambda i: [X[i],y[i]], range(len(X)))))
6.64 ms ± 32.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.array(list(zip(X, y)))
4.53 ms ± 33.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.column_stack((X,y))
19.2 µs ± 30.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.transpose([X,y])
16.2 µs ± 247 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.vstack((X, y)).T
14.2 µs ± 94.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
考虑到所有建议的解决方案,当将数组的大小增加为X
和y
时,np.vstack(X,y).T
是最快的.
Taking into account all proposed solutions, np.vstack(X,y).T
is the fastest when increasing the size of arrayas X
and y
.
这篇关于将1D阵列合并为2D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!