My code is:
x=np.linspace(1,5,5)
a=np.insert(x,np.arange(1,5,1),np.zeros(3))
The output I want is:
[1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0,5]
The error I get is:
ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (4,)
When I do:
x=np.linspace(1,5,5)
a=np.insert(x,np.arange(1,5,1),0)
The out is:
array([1., 0., 2., 0., 3., 0., 4., 0., 5.])
Why it doesn't work when I try to insert an array?
P.S. I I cannot use loops
zeros() function is one of the most significant functions which is used in machine learning programs widely. This function is used to generate an array containing zeros. The numpy. zeros() function provide a new array of given shape and type, which is filled with zeros.
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
zeros() function is used which returns a new array of given shape and type, with zeros.
You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
You can use np.repeat
to feed repeated indices. For a 1d array, thhe obj
argument for np.insert
reference individual indices.
x = np.linspace(1, 5, 5)
a = np.insert(x, np.repeat(np.arange(1, 5, 1), 3), 0)
array([ 1., 0., 0., 0., 2., 0., 0., 0., 3., 0., 0., 0., 4.,
0., 0., 0., 5.])
Another option:
np.hstack((x[:,None], np.zeros((5,3)))).flatten()[:-3]
gives:
array([ 1., 0., 0., 0., 2., 0., 0., 0., 3., 0., 0., 0., 4.,
0., 0., 0., 5.])
That is, pretend x
is a column vector and stack a 5x3 block of zeros to the right of it and then flatten.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With