[Tutor] index of elements in numpy array
eryksun
eryksun at gmail.com
Fri Sep 14 12:05:33 CEST 2012
On Fri, Sep 14, 2012 at 4:36 AM, Bala subramanian
<bala.biophysics at gmail.com> wrote:
>
> 10 # loop over each row
> 11 for i1, d1 in enumerate(b):
> 12 # each x in d1 - value in z corresponding to index of x in d1
> 13 d1=[x-z[d1.index(x)] for x in d1]
>
> If d1 is a simple list, i can fetch the index of its element as
> d1.index(x). So i would like to know how can achieve the same with
> numpy array.
In general you don't want to loop over and enumerate a NumPy array.
That's a lot slower than using vectorized operations (just like in
MATLAB) and broadcasting. See Peter Otten's answer.
For an 'index' operation you have a couple of options. To begin with,
a test returns a bool array:
>>> d = np.array([1,2,1,2,1])
>>> d == 1
array([ True, False, True, False, True], dtype=bool)
You can use this bool array to index the source array:
>>> d[d == 1]
array([1, 1, 1])
>>> d[d == 1] = 3
>>> d
array([3, 2, 3, 2, 3])
To get the indexes, use "nonzero" or "where":
>>> np.nonzero(d == 2)
(array([1, 3]),)
>>> np.where(d == 2)
(array([1, 3]),)
More information about the Tutor
mailing list