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

Question:

I am currently trying to insert an array of shape (640, 1) inside an array of shape (480, 640, 3) to obtain a 481×640 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.

Asked By: Valentin

||

Answers:

To insert in the first dimension:

out = np.insert(a, 0, b[:,None], axis=0)
out.shape
# (481, 640, 3)

Output:

array([[[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        ...,
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        ...,
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        ...,

To insert as in the last dimension, use axis=2:

out = np.insert(a, 0, b, axis=2)
out.shape
# (480, 640, 4)

Output:

array([[[0., 1., 1., 1.],
        [0., 1., 1., 1.],
        [0., 1., 1., 1.],
        ...,
        [0., 1., 1., 1.],
        [0., 1., 1., 1.],
        [0., 1., 1., 1.]],

       [[0., 1., 1., 1.],
        [0., 1., 1., 1.],
        [0., 1., 1., 1.],
        ...,
        [0., 1., 1., 1.],
        [0., 1., 1., 1.],
        [0., 1., 1., 1.]],
Answered By: mozway

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?

Answered By: Zero-nnkn
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.