crippledlambda - 1 year ago 192

Python Question

Does NumPy have a ternary operator? For instance, in R there is a vectorized

`if-else`

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

[1] "a" "a" "b" "b" "b" "b" "b" "b" "b" "b"

Is there anything equivalent in NumPy?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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()`

.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**