37

I have two numpy arrays:

x = np.array([-1, 0, 1, 2])
y = np.array([-2, -1, 0, 1])

Is there a way to merge these arrays together like tuples:

array = [(-1, -2), (0, -1), (1, 0), (2, 1)]
cottontail
  • 10,268
  • 18
  • 50
  • 51
Steven
  • 1,123
  • 5
  • 14
  • 31

2 Answers2

54
In [469]: x = np.array([-1, 0, 1, 2])
In [470]: y = np.array([-2, -1, 0, 1])

join them into 2d array:

In [471]: np.array((x,y))
Out[471]: 
array([[-1,  0,  1,  2],
       [-2, -1,  0,  1]])

transpose that array:

In [472]: np.array((x,y)).T
Out[472]: 
array([[-1, -2],
       [ 0, -1],
       [ 1,  0],
       [ 2,  1]])

or use the standard Python zip - this treats the arrays as lists

In [474]: zip(x,y)   # list(zip in py3
Out[474]: [(-1, -2), (0, -1), (1, 0), (2, 1)]
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • 2
    these results are not tuple data type. – john k Nov 10 '19 at 04:43
  • @johnktejik, `Out[474]` is a list of tuples. `Out[472]` isn't, but for many purposes it is just as good - including the OP's purpose(s). When creating structured arrays the distinction between a list of tuple and a list of lists is significant, but that's an exception. – hpaulj Nov 10 '19 at 05:37
  • 2
    For Python 3, zip returns an iterator instead of a list. This can be converted into a list using ``list(zip(x,y))`` – Mathi Jul 20 '22 at 10:50
1

Concatenation along a second dimension may be done via np.c_[].

x = np.array([-1, 0, 1, 2])
y = np.array([-2, -1, 0, 1])

xy = np.c_[x, y]

# array([[-1, -2],
#        [ 0, -1],
#        [ 1,  0],
#        [ 2,  1]])

If you're after an array of tuples, there's the record arrays:

xy = np.rec.fromarrays([x, y])
# rec.array([(-1, -2), ( 0, -1), ( 1,  0), ( 2,  1)], dtype=[('f0', '<i4'), ('f1', '<i4')])

# convert into a list
xy.tolist()   # [(-1, -2), (0, -1), (1, 0), (2, 1)]
cottontail
  • 10,268
  • 18
  • 50
  • 51