0

How to change an element in np array by index without any loops and if statements. E.g we have array [1,2,3,4], and every second element, starting from 0, I want to change to 10. So as to get [10,2,10,4].

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
12345791
  • 11
  • 3

3 Answers3

0

There you go:

import numpy as np
arr = np.array([1,2,3,4])
for i in range(len(arr)):
  if i%2==0:
    arr[i]=10
print(arr)

Output:

[10  2 10  4]

Without Loop and if Statements:

import numpy as np
arr = np.array([1,2,3,4])
arr[0::2] = 10

Output:

array([10,  2, 10,  4])

I've used Numpy's Slicing which works as [start:stop:step]

itsDV7
  • 854
  • 5
  • 12
0

You can take advantage of NumPy slicing:

a = np.arange(10)
#array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

a[::2] = 10
#array([10,  1, 10,  3, 10,  5, 10,  7, 10,  9])

You can slice an array with the format [start:stop:step]. You can read more here.

Pablo C
  • 4,661
  • 2
  • 8
  • 24
0

Simply, you can use: a[::2]=10

Xyp9x
  • 66
  • 4