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

1

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

1 Comment

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
0
for j in a:
  for i, val in enumerate(b):
    if val == j:
      print(i)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.