0

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?

  • There is plenty of possible duplicates of this one, perhaps you should be more clear in what you are trying to achieve and what your limits / assumptions are. – norok2 Dec 29 '20 at 12:52
  • Does this answer your question? [How to append numpy arrays?](https://stackoverflow.com/questions/41523942/how-to-append-numpy-arrays) – norok2 Dec 29 '20 at 12:52
  • try `np.stack([a,b], axis=2)`. Note also that `np.array([a,b]` produces a (2,3,4) array which can be transpised to (3,4,2) – hpaulj Dec 29 '20 at 14:25

2 Answers2

2

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]]])
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

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

Lukas Schmid
  • 1,895
  • 1
  • 6
  • 18