NumPy ndarray的三元运算符? [英] Ternary operator for NumPy ndarray?

查看:87
本文介绍了NumPy ndarray的三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NumPy是否有三元运算符?例如,在R中有一个向量化的 if-else 函数:

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"

NumPy是否等效?

Is there anything equivalent in NumPy?

推荐答案

您正在寻找 numpy.where()

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甚至有概括(将0、1、2等映射到值,而不是仅映射True和False): numpy.choose()

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

这篇关于NumPy ndarray的三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆