How to vertically combine two arrays in Python?

I want to combine two arrays vertically in Python using the NumPy package:

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

I need something like this:

 c = array([[1,2,3,4],[5,6,7,8]]) 

How can we do this with the concatenate function? I tested these two functions, but the results are the same:

 c = concatenate((a,b),axis=0) # or c = concatenate((a,b),axis=1) 

We have this in both of these functions:

 c = array([1,2,3,4,5,6,7,8]) 
+6
source share
4 answers

The problem is that both a and b are 1D arrays, and therefore only one axis is attached to them.

Instead, you can use vstack (v for vertical):

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

Additionally, row_stack is an alias of the vstack function:

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

It is also worth noting that several arrays of the same length can be stacked at once. For example, np.vstack((a,b,x,y)) will have four lines.

Under the hood, vstack works by making sure that each array has at least two dimensions (using atleast_2D ) and then calls concatenate to combine these arrays on the first axis ( axis=0 ).

+8
source

This may not be a good solution, but it is an easy way to make your code work, just add a change:

 a = array([1,2,3,4]) b = array([5,6,7,8]) c = concatenate((a,b),axis=0).reshape((2,4)) print c 

of

 [[1 2 3 4] [5 6 7 8]] 

In general, if you have more than two arrays with the same length:

 reshape((number_of_arrays, length_of_array)) 
+3
source

To use concatenate , you need to make a and b 2D arrays instead of 1D, as in

 c = concatenate((atleast_2d(a), atleast_2d(b))) 

Alternatively, you can simply do

 c = array((a,b)) 
+2
source

Use np.vstack :

 In [4]: import numpy as np a = np.array([1,2,3,4]) b = np.array([5,6,7,8]) c = np.vstack((a,b)) c Out[4]: array([[1, 2, 3, 4], [5, 6, 7, 8]]) In [5]: d = np.array ([[1,2,3,4],[5,6,7,8]]) d​ Out[5]: array([[1, 2, 3, 4], [5, 6, 7, 8]]) In [6]: np.equal(c,d) Out[6]: array([[ True, True, True, True], [ True, True, True, True]], dtype=bool) 
+2
source

Source: https://habr.com/ru/post/985193/


All Articles