Mke
Mke

Reputation: 3

Selecting certain indices from numpy array and adding 2

import numpy as np
arr = np.array([1,2,3,4,5,6,7,8,9])

How to add 2 to arr[0:2] and arr[5:6] so the final result is:

arr[3,4,3,4,5,8,7,8,9]

Upvotes: 0

Views: 28

Answers (2)

Onyambu
Onyambu

Reputation: 79208

Note that you could create an array that has all the indices to the values that need to be modified:

arr[np.r_[0:2, 5:6]] += 2
print(arr)

Out:

array([3, 4, 3, 4, 5, 8, 7, 8, 9])

Upvotes: 2

jotjern
jotjern

Reputation: 482

Very straight forward :)

import numpy as np

arr = np.array([1,2,3,4,5,6,7,8,9])

arr[0:2] += 2
arr[5:6] += 2

print(arr)

Upvotes: 1

Related Questions