[英]concatenate two arrays in python with alternating the columns in numpy
如何通過從第一個數組中獲取第一列和從第二個數組中獲取第一列,然后從第一列中獲取第二列,從另一個中獲取第二列,等等來連接 numpy python 中的兩個數組? 也就是說,如果我有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])
使用numpy.dstack()
和numpy.flatten()
例程:
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]
如果我們有二維數組,那么我們可以執行以下操作
A = 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.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.