Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a view of a numpy array at specified indexes? (a view from "fancy indexing")

Tags:

python

numpy

What i need is a way to get "fancy indexing" (y = x[[0, 5, 21]]) to return a view instead of a copy.

I have an array, but i want to be able to work with a subset of this array (specified by a list of indices) in such a way that the changes in this subset is also put into the right places in the large array. If i just want to do something with the first 10 elements, i can just use regular slicing y = x[0:10]. That works great, because regular slicing returns a view. The problem is if i don't want 0:10, but an arbitrary set of indices.

Is there a way to do this?

like image 878
Eskil Avatar asked Feb 26 '11 16:02

Eskil


2 Answers

I don't think there is a way around this. My understanding is that 'fancy indexing' will always return a copy. The best solution I can think of is to manipulate y and then use the same fancy indexes to change the values of x afterwards:

ii = [0, 5, 21]
y = x[ii]
<manipulate y>
x[ii] = y
like image 153
JoshAdel Avatar answered Sep 24 '22 20:09

JoshAdel


You can just do:

y = x[[0,1,4]]
func(y)
x[[0,1,4]] = y

I don't think you can get views with fancy indexing. You might not want to, as I think fancy indexing is pretty slow, it should be faster to just copy the data once.

like image 22
wisty Avatar answered Sep 25 '22 20:09

wisty