NumPy ndarray的三元运算符?
NumPy有没有类似于三元运算符的东西?比如在R语言中,有一个可以对向量进行操作的if-else
函数:
> ifelse(1:10 < 3,"a","b")
[1] "a" "a" "b" "b" "b" "b" "b" "b" "b" "b"
在NumPy中有没有类似的功能呢?
1 个回答
43
你在寻找 numpy.where()
这个函数:
>>> print numpy.where(numpy.arange(10) < 3, 'a', 'b')
['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
NumPy 还有一个更通用的函数(它可以把 0、1、2 等数字映射到不同的值,而不仅仅是映射 True 和 False): numpy.choose()
。