Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator for NumPy ndarray?

Tags:

Does NumPy have a ternary operator? For instance, in R there is a vectorized if-else function:

> ifelse(1:10 < 3,"a","b")  [1] "a" "a" "b" "b" "b" "b" "b" "b" "b" "b" 

Is there anything equivalent in NumPy?

like image 409
hatmatrix Avatar asked Oct 21 '11 16:10

hatmatrix


1 Answers

You are looking for numpy.where():

>>> print numpy.where(numpy.arange(10) < 3, 'a', 'b') ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b'] 

NumPy even has a generalization (that maps 0, 1, 2, etc. to values, instead of mapping only True and False): numpy.choose().

like image 183
Eric O Lebigot Avatar answered Sep 19 '22 18:09

Eric O Lebigot