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].
Asked
Active
Viewed 338 times
0
-
1`arr[::2] = 10` – Mr. T Jan 26 '21 at 10:32
3 Answers
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