numpy and python array index question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jenya56
    New Member
    • Nov 2009
    • 14

    numpy and python array index question

    Dear all:

    I have this function and it works just fine but it is slow:

    Code:
    def common_index(list1, list2, val1, val2):
       assert len(list1) == len(list2), "List not of equal length"
       for i in range(len(list1)):
          if list1[i] == val1 and list2[i] == val2:
             return [i] 
    To optimize it:
    coord_ind=numpy.where(list1==val1 and list2==val2)
    Yet this line does not work and always returns ()? Any suggestions? Thanks!!!
    Last edited by bvdet; Dec 1 '09, 09:35 PM. Reason: Add code tags
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    As with my other post you probably want to be working in numpy. And using what I believe are called masks is a great idea.

    We'll change list1 and list2 to array1 and array2. We're looking for a list of the indexes where array1[i]==val1 and array2[i]==val2.

    Code:
    indices=arange(n)   #this creates an array of the indices you're after
    mask1=array1==val1  #this creates an array like [True, False, False, True,...]
    mask2=array2[mask1]==val2  #(no need to check all of the value!)
                                       #array2[mask1] is a smaller array
    return indices[mask1][mask2]
    I haven't tried it yet, but it *should* work, and it *should* be a ton quicker...
    [/CODE]

    Comment

    Working...