-1

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])?

cabralpinto
  • 1,814
  • 3
  • 13
  • 32
  • 3
    Does this answer your question? [Numpy: For every element in one array, find the index in another array](https://stackoverflow.com/questions/8251541/numpy-for-every-element-in-one-array-find-the-index-in-another-array) - particularly https://stackoverflow.com/a/8251668/463796 – w-m Nov 09 '22 at 13:54

2 Answers2

2

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])
Bharat Adhikari
  • 334
  • 1
  • 6
  • I'm aware of this solution, but I was wondering if it would be possible to achieve this using only numpy and without for loops – cabralpinto Nov 09 '22 at 13:53
0
for j in a:
  for i, val in enumerate(b):
    if val == j:
      print(i)
Piotr Żak
  • 2,046
  • 5
  • 18
  • 30