I have a 2 dimensional numpy array:
A = np.zeros(16).reshape(4,4)
I want the (1, 1), (1,3), (3,1)
, and (3,3)
cells to take a value of 1.
A[[1,3], [1:3]] = 1
Only assigns 1 to (1,1)
and (3,3)
.
A[[1,3], :][:, [1, 3]] = 1
Does not work because it make a copy of the data not a view. What's the right way to do this?
Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.
Array indexing is the same as accessing an array element. 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.
Element Assignment in NumPy Arrays We can assign new values to an element of a NumPy array using the = operator, just like regular python lists.
Slicing arrays Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .
Use slices with step=2:
A[1::2,1::2] = 1
Or explictly pass all the indexes:
A[[1,1,3,3],[1,3,1,3]] = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With