0

I have a 2D array size(2,3) and a list

Input:

a=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']

b=[[4 2 8][1 7 0]] #2D numpy array shape (2,3) containing indices of list a

Output:

c = [['deer','bird','ship'],['automobile','horse','airplane']]

Is there any pythonic way or shortcut to achieve the output without iterating over each index value?

6
  • What are you going to do with the output? There might be a better way of representing your data. Commented Apr 20, 2016 at 15:28
  • 3
    it is just a[b] if a is converted in array. Commented Apr 20, 2016 at 15:30
  • 1
    why "without iterating over each index value"? Is there a good reason for that restriction? Commented Apr 20, 2016 at 15:30
  • You can use np.take to have a 2D array as output : np.take(a,b). Commented Apr 20, 2016 at 15:48
  • @TadhgMcDonald-Jensen I have got the array b after a number of operations on numpy array. Also the array b is of shape(n,3) where n is very large over 100000. So I am concerned about the time it will take to iterate using loop. But numpy operation will take less time for sure. Commented Apr 20, 2016 at 15:59

2 Answers 2

2

If you make your list a np.array as well, all you need is a[b]:

>>> import numpy as np
>>> keys = np.array(['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'])
>>> indices = np.array([[4,2,8],[1,7,0]])
>>> keys[indices]
array([['deer', 'bird', 'ship'],
       ['automobile', 'horse', 'airplane']], 
      dtype='<U10')
Sign up to request clarification or add additional context in comments.

Comments

0

This does the job:

a=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
b=numpy.array([[4,2,8],[1,7,0]])


c = [[a[idx] for idx in row] for row in b]

7 Comments

This iterates over each index.
@gr1zzlybe4r Well, as b is a list you have to traverse and index. That's the whole point of a list.
I want to keep the array b as numpy array for further operations for my code
@Kapes I've edited my answer to make b a numpy array. This won't alter the rest of the code. But I'm confused over what you want, or why this wouldn't be acceptable. Keen to help if I can.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.