Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interleave rows of two numpy arrays in Python

I wanted to interleave the rows of two numpy arrays of the same size. I came up with this solution.

# A and B are same-shaped arrays
A = numpy.ones((4,3))
B = numpy.zeros_like(A)
C = numpy.array(zip(A[::1], B[::1])).reshape(A.shape[0]*2, A.shape[1])
print(C)

Outputs

[[ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]]

Is there a cleaner, faster, better, numpy-only way?

like image 399
user394430 Avatar asked Oct 12 '12 14:10

user394430


People also ask

Can you zip NumPy arrays?

If we want to bind or zip the data of different array then we can go for zip function in python of NumPy. This function eliminates the need of class object if not required. We can easily map our data with any number of the array and this can be done very easily with the use of the zip() function.

How do you stack an array depth wise?

The dstack() is used to stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1).

Can you add two NumPy arrays?

To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are​ not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.

How do I serialize a NumPy array into JSON in Python?

Use the cls kwarg of the json. dump() and json. dumps() method to call our custom JSON Encoder, which will convert NumPy array into JSON formatted data. To serialize Numpy array into JSON we need to convert it into a list structure using a tolist() function.


1 Answers

It is maybe a bit clearer to do:

A = np.ones((4,3))
B = np.zeros_like(A)

C = np.empty((A.shape[0]+B.shape[0],A.shape[1]))

C[::2,:] = A
C[1::2,:] = B

and it's probably a bit faster as well, I'm guessing.

like image 162
JoshAdel Avatar answered Sep 19 '22 08:09

JoshAdel