Reputation: 139
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?
Upvotes: 5
Views: 4916
Reputation: 221744
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')
Upvotes: 4
Reputation: 477794
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')
Upvotes: 2
Reputation: 78790
>>> bool_arr = [True, True, False]
>>> ['r' if x else 'k' for x in bool_arr]
['r', 'r', 'k']
Upvotes: 5