Search code examples
pythonarraysnumpyinsertpython-itertools

Insert 1D array into a 2D array


I am trying to insert a column into a 2D array. Currently I have a 2D array generated using itertools.

sample_points=[-1.5, -.8]
base_points = itertools.combinations_with_replacement(sample_points, 3)
base_points_list=list(base_points)
base_points_array=np.asarray(base_points_list)

Then I get an array which looks like this:

>>> base_points_array
array([[-1.5, -1.5, -1.5],
       [-1.5, -1.5, -0.8],
       [-1.5, -0.8, -0.8],
       [-0.8, -0.8, -0.8]])

I want to add a column at the beginning so that the array looks like this:

[[1 -1.5 -1.5 -1.5]
 [1 -1.5 -1.5 -0.8]
 [1 -1.5 -0.8 -0.8]
 [1 -0.8 -0.8 -0.8]]

So I used the command: np.insert(base_points_array,0,1,1) Because it should be able to do that using broadcasting. but I get something completely different. the number of rows have changes:

array([[ 1. , -1.5, -1.5, -1.5, -0.8],
       [ 1. , -1.5, -1.5, -0.8, -0.8],
       [ 1. , -1.5, -0.8, -0.8, -0.8]])

What am I doing wrong?


Solution

  • Using the np.append . But if your array to insert is 1D array

    insert_array= [1, 1, 1, 1]

    You need to expand the dimension of your inserting array by 1 first, you can do it with

    insert_array= np.expand_dims(insert_array, 1)

    And then you can use the append method

    base_points_array= np.append(insert_array, base_points_array, 1)