Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the values of a NumPy array that are NOT in a list of indices

I have a NumPy array like:

a = np.arange(30) 

I know that I can replace the values located at positions indices=[2,3,4] using for instance fancy indexing:

a[indices] = 999 

But how to replace the values at the positions that are not in indices? Would be something like below?

a[ not in indices ] = 888 
like image 210
Saullo G. P. Castro Avatar asked Jun 05 '13 13:06

Saullo G. P. Castro


People also ask

How do I remove a specific indices from a NumPy array?

To remove an element from a NumPy array: Specify the index of the element to remove. Call the numpy. delete() function on the array for the given index.

How do I replace missing values in NumPy?

In NumPy, to replace missing values NaN ( np. nan ) in ndarray with other numbers, use np. nan_to_num() or np. isnan() .


1 Answers

I don't know of a clean way to do something like this:

mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool) mask[indices] = False a[~mask] = 999 a[mask] = 888 

Of course, if you prefer to use the numpy data-type, you could use dtype=np.bool_ -- There won't be any difference in the output. it's just a matter of preference really.

like image 123
mgilson Avatar answered Oct 12 '22 14:10

mgilson