Reputation:
Is there is a vectorized (or better) way of setting values to certain data points of numpy array based on another way other than this way?
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
pos = np.array([[1, 2], [2, 0]])
for p in pos:
i,j = p
data[i,j] = 20
print(data)
Upvotes: 2
Views: 336
Reputation:
Just extending the great answer by @piRSquared.
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9],[10,11,12]])
pos = np.array([[1.0, 2.0,0.03], [2.0, 0.0,0.06]])
data = data.astype(float)
data[pos[:,0:2].astype(int).tolist()] = pos[:,-1]
data
array([[ 1. , 2. , 3. ],
[ 4. , 5. , 0.03],
[ 0.06, 8. , 9. ],
[ 10. , 11. , 12. ]])
Upvotes: 0
Reputation: 294258
With later versions of Python you can create a list within a comprehension by unpacking another iterable. We then pass that list to do slice assignment.
The way we are accessing (slicing) is done via Integer Array Indexing
data[[*pos]] = 20
data
array([[ 1, 2, 3],
[ 4, 5, 20],
[20, 8, 9]])
For other versions of Python try:
data[pos.tolist()] = 20
data
Upvotes: 3