2

I have a string say s='abcd...z', and a multi-dimensional numpy array - for example arr = [[2, 5, 11], [1, 3, 9]]. How can I use the array as an index into the string? The output I want is str_arr = [['b', 'e', 'k'],['a', 'c', 'i']].

I can do this using list comprehensions or for loops, but I am not sure if those are the fastest methods (especially if the array is large). Any vectorized methods? Also looking for something which works not just got 2d arrays but any dimension.

2 Answers 2

3

You can vectorize it to by creating a mapping array:

import string
import numpy as np
map = np.array(list(string.ascii_lowercase))
arr = np.array([[2, 5, 11], [1, 3, 9]])
map[arr-1]

Result:

array([['b', 'e', 'k'],
       ['a', 'c', 'i']], dtype='<U1')
Sign up to request clarification or add additional context in comments.

Comments

0

Just for other's information, using for loops, in a 2D array:

[[s[i] for i in arr[j]] for j in range(len(arr))]

Comments

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.