基于复杂条件选择和重新分配数组中元素的最快方法

时间:2013-03-21 23:00:41

标签: python arrays numpy scipy

根据numpy中的复杂条件选择和重新分配元素的最快方法是什么,例如:

# some 1-d array of floats
myarray = np.array(myarray)
# set any foo's or bar's from myarray to 0
myarray[where(map(lambda x: foo(x) or bar(x), myarray))] = 0

是使用np.vectorize的解决方案吗?还是np.select

2 个答案:

答案 0 :(得分:1)

最快的可能是使用包含所有条件的数组的花式索引:

import numpy as np
x = np.arange(1000)
cond1 = x % 2 == 0      # getting the even numbers
cond2 = x**0.5 % 1 == 0 # getting those with exact square root
cond3 = x % 3 == 0      # getting those divisible by 3
cond =np.all(np.array((cond1,cond2,cond3)),axis=0)
print x[ cond ]
#[  0  36 144 324 576 900] 

使用np.all表示cond1和cond2和cond3。

使用np.any表示cond1或cond2或cond3。

如果所有条件都是在预先设定的布尔数组中创建的话,这会更快:

conds = np.zeros((3,1000),dtype='bool')

然后将每个条件分配给数组中的一行。

答案 1 :(得分:0)

也可以使用np.where():

In [7]: a[np.where((a % 2 == 0) & (a % 3 == 0) & (a ** 0.5 % 1 == 0))]
Out[7]: array([  0,  36, 144, 324, 576, 900])
相关问题