How to add a number in a specific location in a numpy array

Viewed 579

I want to add a certain number, in this case 1, to a specific location in the array specified below

array = np.zeros((1, 5))

If I run the code above, I get an array that looks like this

[0,0,0,0,0]

How do I add the integer 1 in a specific location in this array? I know if you use

np.add(array,1)

you get something like

[1,1,1,1,1]

What should I do I want to add 1 only in a specific location in the numpy array so it'll look more like

[1,0,0,0,0] or [0,0,1,0,0]
2 Answers

This is a 1D array in Numpy:

>>> a1=np.zeros(5)
>>> a1[2]=1
>>> a1
array([0., 0., 1., 0., 0.])

This creates a 2D array even though it only has one row:

>>> array = np.zeros((1, 5))
>>> array
array([[0., 0., 0., 0., 0.]])

If you try to assign the same way, error:

>>> array[2]=1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 1

Or, more confusingly, if you assign thinking it is to a single element, for 2D, Numpy assumes a default axis and will assign all the values in that row:

>>> array = np.zeros((1, 5))
>>> array[0]=3
>>> array
array([[3., 3., 3., 3., 3.]])

To assign to a single element in a 2D array, you need to use row and column index:

>>> array[0,2]=1
>>> array
array([[0., 0., 1., 0., 0.]])

Use the location index to add the value:

array[0,0] += 1
#[[1,0,0,0,0]]

array[0,2] += 1
#[[0,0,1,0,0]]
Related