Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fancy indexing with assignment for numpy array

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?

like image 401
fgregg Avatar asked Feb 22 '15 21:02

fgregg


People also ask

What is NumPy fancy indexing?

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.

Can NumPy arrays be indexed?

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.

How do I assign an element to a NumPy array?

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.

What is NumPy array explain with the help of indexing and slicing operations?

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] .


1 Answers

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
like image 134
shx2 Avatar answered Sep 21 '22 01:09

shx2