[Tutor] index of elements in numpy array

Peter Otten __peter__ at web.de
Fri Sep 14 11:02:22 CEST 2012


Bala subramanian wrote:

> Thank you all for the answer. Below, i have pasted a sample code that
> shows what i am intending to do. The code fails at line 13 as numpy
> array dnt have a index attribute.
> 
>   1 #!/usr/bin/env python
>   2 import numpy as np
>   3
>   4 a=np.array([1,2,3,4,5,6,7,8,9,10,11,12])
>   5
>   6 b=np.reshape(a,(3,4))
>   7
>   8 z=[100,101,102,103,104,106,107,108,109,110,111,112]
>   9
>  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.

How about

>>> b - np.array(z[:4])
array([[-99, -99, -99, -99],
       [-95, -95, -95, -95],
       [-91, -91, -91, -91]])

(Note that the result may differ from that of your code if d1 contains 
duplicate values)



More information about the Tutor mailing list