Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge ith values of two different array in one array python

I have one solution for particular problem as

[[0.34 0.26 0.76 ]
 [0.79 0.82 0.37 ]
 [0.93 0.87 0.94]]

I have another solution for same problem as

[[0.21 0.73 0.69 ]
 [0.35 0.24 0.53]
 [0.01 0.42 0.50]]

Now I have to merge their ith position together so the resultant array would be like

[[0.34 0.21]
[0.26 0.73]
[0.76 0.69]
[0.79 0.35]
..........
..........
like image 868
DunJen.coder Avatar asked Mar 06 '23 23:03

DunJen.coder


2 Answers

Setup

x = np.array([[0.34, 0.26, 0.76 ],  [0.79, 0.82, 0.37 ],  [0.93, 0.87, 0.94]])
y = np.array([[0.21, 0.73, 0.69 ],  [0.35, 0.24, 0.53],  [0.01, 0.42, 0.50]])

dstack and ravel

np.dstack([x.ravel(), y.ravel()])

array([[[0.34, 0.21],
        [0.26, 0.73],
        [0.76, 0.69],
        [0.79, 0.35],
        [0.82, 0.24],
        [0.37, 0.53],
        [0.93, 0.01],
        [0.87, 0.42],
        [0.94, 0.5 ]]])

If you're concerned with the extra dimension this introduces, you can vstack and transpose:

np.vstack([x.ravel(), y.ravel()]).T

array([[0.34, 0.21],
       [0.26, 0.73],
       [0.76, 0.69],
       [0.79, 0.35],
       [0.82, 0.24],
       [0.37, 0.53],
       [0.93, 0.01],
       [0.87, 0.42],
       [0.94, 0.5 ]])

Another alternative using np.column_stack

np.column_stack([x.ravel(), y.ravel()])
like image 91
user3483203 Avatar answered Apr 27 '23 01:04

user3483203


You can use vstack on your 2 arrays and reshape appropriately:

np.vstack([arr1,arr2]).reshape(2,-1).T

Example:

>>> arr1
array([[ 0.34,  0.26,  0.76],
       [ 0.79,  0.82,  0.37],
       [ 0.93,  0.87,  0.94]])
>>> arr2
array([[ 0.21,  0.73,  0.69],
       [ 0.35,  0.24,  0.53],
       [ 0.01,  0.42,  0.5 ]])

>>> np.vstack([arr1,arr2]).reshape(2,-1).T
array([[ 0.34,  0.21],
       [ 0.26,  0.73],
       [ 0.76,  0.69],
       [ 0.79,  0.35],
       [ 0.82,  0.24],
       [ 0.37,  0.53],
       [ 0.93,  0.01],
       [ 0.87,  0.42],
       [ 0.94,  0.5 ]])
like image 33
sacuL Avatar answered Apr 27 '23 00:04

sacuL