如何在numpy python中连接两个数组,通过从第一个数组中获取第一列和从第二个数组中获取第一列,然后从第一个数组中获取第二列和从另一个数组中获取第二列等等。也就是说,如果我有
A=[a1 a2 a3]
和B=[b1 b2 b3]
,我希望得到的结果数组为[a1 b1 a2 b2 a3 b3]
。A=[a1 a2 a3]
和B=[b1 b2 b3]
,我希望得到的结果数组为[a1 b1 a2 b2 a3 b3]
。np.vstack((A,B)).ravel('F')
np.stack((A,B)).ravel('F')
np.ravel([A,B],'F')
样例运行 -
In [291]: A
Out[291]: array([3, 5, 6])
In [292]: B
Out[292]: array([13, 15, 16])
In [293]: np.vstack((A,B)).ravel('F')
Out[293]: array([ 3, 13, 5, 15, 6, 16])
In [294]: np.ravel([A,B],'F')
Out[294]: array([ 3, 13, 5, 15, 6, 16])
ravel
无论输入形状如何都会输出一个1D数组。 - Sunreefnp.stack((A,B),2).reshape(A.shape[0],-1)
。 - hpauljA = np.zeros((5,2))
B = np.ones((5,2))
row_a, col_a = np.shape(A)
row_b, col_b = np.shape(B)
assert row_a == row_b, 'number of rows should be same'
np.ravel([A,B],order="F").reshape(row_a,col_a+col_b)
这将提供
array([[0., 1., 0., 1.],
[0., 1., 0., 1.],
[0., 1., 0., 1.],
[0., 1., 0., 1.],
[0., 1., 0., 1.]])
assert col_a == col_b, 'number of cols should be same'
np.ravel([A,B],order="F").reshape(col_a,row_a+row_b).T
这将会给予
array([[0., 0.],
[1., 1.],
[0., 0.],
[1., 1.],
[0., 0.],
[1., 1.],
[0., 0.],
[1., 1.],
[0., 0.],
[1., 1.]])
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.dstack((a,b)).flatten()
print(result)
输出:
[1 4 2 5 3 6]
zip(A,B)
?任何其他的压缩方式都会导致列表/元组输出。这样做不会得到数组输出,OP已经提到他们想要一个数组输出。将任何基于压缩的列表结果转换为数组的开销对性能不利,这就是为什么在NumPy领域中压缩并不太流行的原因。 - Divakar