Given the object data
, which is of type numpy.ndarray
, how can I perform the following in one line?
VERY_LOW = np.where(data<=-2, 'VERY_LOW', 'LOL').astype('S12')
LOW = np.where((data>-2) & (data<=-1), 'LOW', VERY_LOW)
AVERAGE = np.where((data>-1) & (data<+1), 'AVERAGE', LOW)
HIGH = np.where((data>=+1) & (data<+2), 'HIGH', AVERAGE)
VERY_HIGH = np.where(data>=+2, 'VERY_HIGH', HIGH)
Basically, what I am trying to achieve is to assign a tag to each cell depending on its value (one out of five available).
You could write a function that maps a value to a tag, and then use the np.vectorize
function to apply it.
def map_func(x):
if x <= -2:
return 'VERY LOW'
elif <= -1:
return 'LOW'
# Keep adding more conditions here
else:
return 'OTHER'
vec_map_func = np.vectorize(map_func)
tag_array = vec_map_func(data)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments