Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy function to set elements of array to a value given a list of indices

I'm looking for a numpy function that will do the equivalent of:

indices = set([1, 4, 5, 6, 7])
zero    = numpy.zeros(10)
for i in indices:
    zero[i] = 42
like image 448
involucelate Avatar asked Dec 04 '11 03:12

involucelate


People also ask

How do I assign a value to a NumPy array in Python?

We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).

How do you select values from an NP array?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.

Do NumPy arrays have indices?

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.

How do you assign an index to an array?

Instead, go for something like: ... [2] => stdClass Object ( [qty] => 2 [id] => 2 [name] => Single 1 Tag Innenraum 2 [one] => Array( [name] => jiya [sirname] => rathod ) [two] => Array( [name] => jiya [sirname] => rathod ) ...


2 Answers

You can just give it a list of indices:

indices = [1, 4, 5, 6, 7]
zero = numpy.zeros(10)
zero[indices] = 42
like image 154
stranac Avatar answered Oct 12 '22 03:10

stranac


If you have an ndarray:

>>> x = np.zeros((3, 3, 3))
>>> y = [0, 9, 18]
>>> x
array([[[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]]])
>>> np.put(x, y,  1)
>>> x
array([[[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

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

       [[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])
like image 43
Sun Avatar answered Oct 12 '22 03:10

Sun