np.where的"case"等效方法是什么?

11

np.where允许您选择要为布尔类型查询分配的值,例如:

test = [0,1,2]
np.where(test==0,'True','False')
print test
['True','False','False']

这基本上是一个“if”语句。是否有一种Pythonic的方法,可以为numpy数组编写类似于“if、else if、else”的语句(具有不同的情况)?

以下是我的解决方案:

color = [0,1,2]
color = np.where(color==0,'red',color)
color = np.where(color==1,'blue',color)
color = np.where(color==2,'green',color)
print color
['red','blue','green']

但我想知道是否有更好的方法来做这件事。

3个回答

11

numpy.select() 是你所需的工具。它是 numpy 版本的 case when。语法:

import numpy as np
color = np.array([0,1,2])
condlist = [color == 1, color == 2, color == 3]
choicelist = ['red', 'blue', 'green']
np.select(condlist, choicelist, default='unknown')

返回:

array(['unknown', 'red', 'blue'], dtype='<U7')

3

np.choose 是一种多元素的 where

In [97]: np.choose([0,1,1,2,0,1],['red','green','blue'])
Out[97]: 
array(['red', 'green', 'green', 'blue', 'red', 'green'], 
      dtype='<U5')
In [113]: np.choose([0,1,2],[0,np.array([1,2,3])[:,None], np.arange(10,13)])
Out[113]: 
array([[ 0,  1, 12],
       [ 0,  2, 12],
       [ 0,  3, 12]])

在更复杂的情况下,熟练掌握广播技术有助于解决问题。
例如,选择数量不能超过32个。它的使用率远不及np.where。
有时,您只需要多次应用where或布尔遮罩。
In [115]: x
Out[115]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [116]: x[x<4] += 10
In [117]: x
Out[117]: 
array([[10, 11, 12, 13],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [118]: x[x>8] -=3
In [119]: x
Out[119]: 
array([[ 7,  8,  9, 10],
       [ 4,  5,  6,  7],
       [ 8,  6,  7,  8]])
In [120]: x[(4<x)&(x<8)] *=2
In [121]: x
Out[121]: 
array([[14,  8,  9, 10],
       [ 4, 10, 12, 14],
       [ 8, 12, 14,  8]])

0

其中一种更符合Python风格的方法是使用列表推导式,就像这样:

>>> color = [0,1,2]
>>> ['red' if c == 0 else 'blue' if c == 1 else 'green' for c in color]
['red', 'blue', 'green']

如果你仔细阅读,它就相当直观。对于列表中的给定项color,新列表中的值将为'red'(如果颜色为0),'blue'(如果颜色为1),否则为'green'。不过,我不知道是否应该在列表推导式中使用超过三个的if else。在那种情况下,使用for循环会更合适。

或者你可以使用一个字典,这可能更符合“Pythonic”的风格,并且可扩展性更强:

>>> color_dict = {0: 'red', 1: 'blue', 2: 'green'}
>>> [color_dict[number] for number in color]
['red', 'blue', 'green']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接