1
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
b=np.array([[1,2,3],[4,5,6],[7,8,9]])

I've 2 identical 2D arrays, I'm trying to zip them element-wise. It should look like:


[[(1,1) (2,2), (3,3)]
[(4,4) (5,5) (6,6)]
[(7,7) (8,8) (9,9)]]

I've tried the method below but it didn't work out. First flatten the arrays, zip them, convert it into a list, then convert it into an array and reshape it.

np.array(list(zip(np.ndarray.flatten(a),np.ndarray.flatten(b)))).reshape(a.shape)

I'm getting the following error

cannot reshape array of size 18 into shape (3,3)

It's not treating the elements (1,1) (2,2) etc. of the final array as tuples but as individual elements. Hence, 18 elements.

This question has been posted once but I didn't find an answer that worked for me.

Pixel_Bear
  • 97
  • 1
  • 1
  • 11
  • An `ndarray` of tuples isn't going to be more useful than an equivalent linked list. `numpy` is for doing math, and you can't math tuples without unraveling them natively (complex number formats notwithstanding). Do you instead want an array with a final dimension of `2`? – Daniel F Nov 18 '22 at 10:16
  • @DanielF Ideally yes. But I can manage with a 3D array too. – Pixel_Bear Nov 18 '22 at 12:03

1 Answers1

1

Don't zip, use numpy native functions! You want a dstack:

out = np.dstack([a, b])

output:

array([[[1, 1],
        [2, 2],
        [3, 3]],

       [[4, 4],
        [5, 5],
        [6, 6]],

       [[7, 7],
        [8, 8],
        [9, 9]]])
mozway
  • 194,879
  • 13
  • 39
  • 75
  • ```np.dstack([a,b)``` gives me a 3D array. I can manage with this but just for the sake of convinience, can array elements be stored as tuples, i.e. I want element of the form (1,1), with array shape (3,3)? @mozway – Pixel_Bear Nov 18 '22 at 12:02
  • 2
    Storing as tuples would implicate that you have to use an `object` dtypes, meaning that you won't benefit from most of the vectorized operations. If you really need to do this, use [this recipe](https://stackoverflow.com/questions/43426039/convert-last-dimension-of-ndarray-to-tuple-recarray). – mozway Nov 18 '22 at 12:23
  • 1
    Got it, for me there's no point in having it in form of tuples then @mozway – Pixel_Bear Nov 18 '22 at 12:26