Reputation: 11
I want to append two NumPy arrays. These two arrays have the same shape and I would like to append each element of two arrays and store it in another NumPy array which has a less computational cost. for example:
a = np.arange (12).reshape(4,3)
b = np.arange (2,14).reshape(4,3)
I would like to create the following np.array:
c = [[ (0,2) (1,3) (2,4)]
[ (3,5) (4,6) (5,7)]
[ (6,8) (7,9) (8,10)]
[(9,11) (10,12) (11,13)]]
it should be noted that by using for loop it can be created, but the computational cost for higher dimension is huge. it is better to use vectorized way. Could you please tell me how can create this np.array?
Upvotes: 0
Views: 1122
Reputation: 1960
Using dstack and reshape, you can both zip and reform them.
np.dstack((a, b)).reshape(4,3,2)
That leaves you with
[[[ 0 2]
[ 1 3]
[ 2 4]]
[[ 3 5]
[ 4 6]
[ 5 7]]
[[ 6 8]
[ 7 9]
[ 8 10]]
[[ 9 11]
[10 12]
[11 13]]]
Which should provide the same functionality as tuples would. I've tried multiple approaches, but didn't manage to keep actual tuples in the numpy array
Upvotes: 0
Reputation: 96360
It is not exactly clear what shape you are expecting, but I believe you are looking for numpy.dstack
:
>>> a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> b
array([[ 2, 3, 4],
[ 5, 6, 7],
[ 8, 9, 10],
[11, 12, 13]])
>>> np.dstack([a,b])
array([[[ 0, 2],
[ 1, 3],
[ 2, 4]],
[[ 3, 5],
[ 4, 6],
[ 5, 7]],
[[ 6, 8],
[ 7, 9],
[ 8, 10]],
[[ 9, 11],
[10, 12],
[11, 13]]])
Upvotes: 2