Search code examples
pythonnumpyfor-loopnumpy-ndarray

Using np.where to find indices of array


If I have an array :

array = 'KDI', 'KDI', 'KDU', 'KDA', 'ANU', 'AMU', 'BDU', 'CDU',
       'CDU', 'DAI', 'DAH', 'DBD', 'DDT', 'DDT', 'DDB', 'DDB',
       'UDM', 'UDM', 'DMA', 'DMH', 'DSX'], dtype='<U4')

and I apply :

for name in array:
    if name in array :
        idx_lookup = np.where(name==array)[0][0]
        print(idx_lookup)`

I got the result

0
0
2
3
4
5
6
7
7
9
10
11
12
12
14
14
16
16
18
19
20

meanhwile, what I want is, [0,1,2,3,4,...,20]. I want to find where is the match indices between two arrays using this for and if loop. in this case, I use exact same array, but I also want it applicable if the array are different and I want to find where is the same indices. where is the mistake in the code ?

thanks


Solution

  • You have some duplicates in your array. You could count the duplicates in a dictionary. Then return the index of the position of that exact value even if its a duplicate.

    array=np.array(['KDI', 'KDI', 'KDU', 'KDA', 'ANU', 'AMU', 'BDU', 'CDU',
           'CDU', 'DAI', 'DAH', 'DBD', 'DDT', 'DDT', 'DDB', 'DDB',
           'UDM', 'UDM', 'DMA', 'DMH', 'DSX'], dtype='<U4')
    
    found={}
    for name in array:
        if name in array :
    
            if found.get(name) == None:
                found[name]=0
            else:
                found[name]+=1
            idx_lookup = np.where(name==array)[0][found[name]]
            print(idx_lookup)