5

I have a boolean array like such

bool_arr = [True, True, False]

And I want to map two Strings onto each boolean value

string_arr = ['r', 'r, 'k']

How would I map this using numpy?

3
  • Those are numpy arrays? Commented Mar 10, 2017 at 13:18
  • Yes, I've just shown them like this for shorthand Commented Mar 10, 2017 at 13:19
  • "map two Strings onto each boolean value" -- don't know what that means. Map True to "r" and False to "k"? Commented Mar 10, 2017 at 13:20

3 Answers 3

5
>>> bool_arr = [True, True, False]
>>> ['r' if x else 'k' for x in bool_arr]
['r', 'r', 'k']
Sign up to request clarification or add additional context in comments.

Comments

4

Vectorized approaches using indexing -

bool_arr = np.array([True, True, False]) # Input boolean array
strings = np.array(['k','r']) # Input array of strings for mapping

out = np.take(strings, bool_arr)
out = np.take(strings, bool_arr.astype(int))
out = strings[bool_arr.astype(int)]

Using np.where if we need to choose between just two strings -

np.where(bool_arr, 'r','k')

Comments

2

You can use the numpy.vectorize method:

import numpy as np

x = np.array([True, True, False])
mapping = ('k','r')
result = np.vectorize(lambda i:mapping[i])(x)

which gives:

>>> result
array(['r', 'r', 'k'], 
      dtype='<U1')

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.