Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two arrays vertically to array of tuples using numpy

Tags:

python

numpy

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 tupples:

array = [(-1, -2), (0, -1), (1, 0), (2, 1)] 
like image 924
Steven Avatar asked Jan 29 '16 18:01

Steven


People also ask

How do I merge two arrays vertically in Python?

Use np. vstack() to concatenate two arrays vertically Call np. vstack(array1, array2) to concatenate array1 and array2 vertically.

How do I concatenate a NumPy array vertically?

NumPy: vstack() function The vstack() function is used to stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). The arrays must have the same shape along all but the first axis.

How do I merge two NumPy arrays in Python?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

How do you combine two arrays horizontally in Python?

hstack() function. The hstack() function is used to stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.


1 Answers

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)] 
like image 152
hpaulj Avatar answered Oct 14 '22 18:10

hpaulj