Concatenate 1D and 2D arrays as per index position

python 2d array indexing
numpy array
numpy create 2d array
numpy slice 2d array
numpy reshape 1d to 2d
numpy stack
how to append two 2d arrays in python
numpy vstack

I am trying to concatenate a 1D into a 2D array. I'd like to avoid doing a loop as it's very computer intensive if my array lengths are greater than 1000.

I have tried vstack, stack and concatenate with no success.

import numpy as np

array_a = np.array([1,2,3])

array_b = np.array([[10, 11, 12], [20, 21, 22], [30, 31, 32]])

The expected output should be

array([[1, 10, 11, 12], [2, 20, 21, 22], [3, 30, 31, 32]])

Many thanks for your help!


Mykola showed the right way to do this, but I suspect you need a little help in understanding why. You tried several things without telling us what was wrong.

In [241]: array_a = np.array([1,2,3]) 
     ...: array_b = np.array([[10, 11, 12], [20, 21, 22], [30, 31, 32]])  

vstack runs:

In [242]: np.vstack((array_a, array_b))                                         
Out[242]: 
array([[ 1,  2,  3],
       [10, 11, 12],
       [20, 21, 22],
       [30, 31, 32]])

But the result is a vertical join, by rows, not columns. The v in vstack is supposed to remind us of that.

stack tries to join the arrays on a new axis, and requires that all input array have a matching shape:

In [243]: np.stack((array_a, array_b))                                          
...
ValueError: all input arrays must have the same shape

I suspect you tried this at random, without really reading the docs.

Both of these use concatenate, which is the basic joiner. But it's picky about dimensions:

In [244]: np.concatenate((array_a, array_b))                                    
...
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)

You clearly realized that the number of dimensions didn't match.

You want to make a (3,4) array. One is (3,3), the other needs to be (3,1). And join axis needs to be 1

In [247]: np.concatenate((array_a[:,None], array_b), axis=1)                    
Out[247]: 
array([[ 1, 10, 11, 12],
       [ 2, 20, 21, 22],
       [ 3, 30, 31, 32]])

If we made a (1,3) array, and tried to join on the default 0 axis, we get the same thing as the vstack. In fact that's what vstack does:

In [248]: np.concatenate((array_a[None,:], array_b))                            
Out[248]: 
array([[ 1,  2,  3],
       [10, 11, 12],
       [20, 21, 22],
       [30, 31, 32]])

Another function is:

In [249]: np.column_stack((array_a, array_b))                                   
Out[249]: 
array([[ 1, 10, 11, 12],
       [ 2, 20, 21, 22],
       [ 3, 30, 31, 32]])

This does the same thing as [247].

Functions like vstack and column_stack are handy, but in long run it's better to understand how to use concatenate itself.

Concatenating arrays in Numpy, We can also concatenate these two 1D arrays using numpy r_ . You can concatenate the above 2D arrays using vstack and will get the same  How to Concatenate Multiple 1d-Arrays? NumPy’s concatenate function can also be used to concatenate more than two numpy arrays. Here is an example, where we have three 1d-numpy arrays and we concatenate the three arrays in to a single 1d-array. Let use create three 1d-arrays in NumPy. x = np.arange(1,3) y = np.arange(3,5) z= np.arange(5,7)


You want insert:

import numpy as np

array_a = np.array([1, 2, 3])

array_b = np.array([[10, 11, 12], [20, 21, 22], [30, 31, 32]])

result = np.insert(array_b, 0, array_a, axis=1)
print(result)

Output

[[ 1 10 11 12]
 [ 2 20 21 22]
 [ 3 30 31 32]]

How to reshape a 1D NumPy array to a 2D NumPy array in Python, How do you convert 1d to 2d array in Python? Introduction to 2D Arrays In Python. Arrangement of elements that consists of making an array i.e. an array of arrays within an array. A type of array in which the position of a data element is referred by two indices as against just one, and the entire representation of the elements looks like a table with data being arranged as rows and columns, and it can be effectively used for performing


You can reshape() the first array and then concatenate() both arrays:

np.concatenate([array_a.reshape(3, -1), array_b], axis=1)

NumPy Array manipulation: vstack() function, after row-wise concatenation is of the shape 6 x 3, i.e. 6 rows and 3 columns. numpy.concatenate¶ numpy.concatenate ((a1, a2, ), axis=0, out=None) ¶ Join a sequence of arrays along an existing axis. Parameters a1, a2, … sequence of array_like The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).


How To Concatenate Arrays in NumPy?, Which of the following Numpy method is used to join arrays vertically? One way of concatenating multiple arrays is by using Build Array function. This function works in two modes: either appending elements to an n-dimensional array, which is the default mode, or concatenating multiple arrays. The Build Array function will work in concatenate mode when Concatenate Inputs has been selected from the shortcut menu


numpy.vstack() in python, about arrays¶. This section covers 1D array , 2D array , ndarray , vector , matrix that you want to keep. To read more about concatenate, see: concatenate . You can use np.expand_dims to add an axis at index position 1 with: >>> In this example, a tuple of arrays was returned: one for each dimension. The first array  Accessing Values in a Two Dimensional Array. The data elements in two dimesnional arrays can be accessed using two indices. One index referring to the main or parent array and another index referring to the position of the data element in the inner array. If we mention only one index then the entire inner array is printed for that index position.


the absolute basics for beginners, Then we would have one sample per day, and the features would be the temperature, wind, Accessing arrays with indexing and slicing; Reshaping of arrays; Combining and Two dimensional array can be given by listing the rows of the array: has shape {b.shape}: {b}") np.concatenate((a,b)) # concatenating 1d arrays. Combining data¶. For combining datasets or data arrays along a single dimension, see concatenate.. For combining datasets with different variables, see merge.. For combining datasets or data arrays with different indexes or missing values, see combine.