Home > database >  Turning each element in a numpy array into its index in another array
Turning each element in a numpy array into its index in another array

Time:11-09

How can I turn each element in a numpy array into its index in another array?

Take the following example. Let a = np.array(["a", "c", "b", "c", "a", "a"]) and b = np.array(["b", "c", "a"]). How can I turn each element in a into its index in b to obtain c = np.array([2, 1, 0, 1, 2, 2])?

CodePudding user response:

We can solve this problem in easy way as follow using Dictionary in python

import numpy as np
a = np.array(["a", "c", "b", "c", "a", "a"])

b = np.array(["b", "c", "a"])

# Create hashmap/dictionary to store indexes 
hashmap ={}
for index,value in enumerate(b):
    hashmap[value]=index

# Create empty np array to store results
c=np.array([])

# Check the corresponding index using hashmap and append to result
for value in a:
    c= np.append(c,hashmap[value])

CodePudding user response:

for j in a:
  for i, val in enumerate(b):
    if val == j:
      print(i)
  • Related