本文介绍了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?

推荐答案

您正在寻找:

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 even has a generalization (that maps 0, 1, 2, etc. to values, instead of mapping only True and False): numpy.choose().

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

10-29 09:53