Search code examples
pythonarraysnumpyinsert

I need to insert a numpy array of a different shape than my other arrays


I am currently trying to insert an array of shape (640, 1) inside an array of shape (480, 640, 3) to obtain a 481x640 array where the first column is juste a line of 640 objects and the other columns are arrays of shape (640, 3).

I tried this:

a=ones((480, 640, 3))
b=zeros(640)
insert(a, 0, b, axis=0)

But I get the error : ValueError: could not broadcast input array from shape (1,1,640) into shape (1,640,3).

Which I understand, as my arrays inside have a different shape than b, but I don't know how to fix this.

Have a gerat day and thanks for the feedbacks.


Solution

  • You must resize b to (640, 1). So, when you insert b to the first axis of a, numpy will broadcast (640, 1) to (640, 3) to fit with the remaining dimensions. Then, first dimension will be increased from 480 -> 481.

    a = np.ones((480, 640, 3))
    b = np.zeros((640, 1))
    a = np.insert(a, 0, b, axis=0)
    a.shape
    # (481, 640, 3)
    

    Is this what you mean?