根据 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
也许?
最佳答案
最快的可能是使用包含所有条件的数组的花式索引:
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。
如果所有条件都在预定义的 bool 值数组中创建,这会更快:
conds = np.zeros((3,1000),dtype='bool')
然后将每个条件分配给数组中的一行。
关于python - 根据复杂条件选择和重新分配数组中元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15559799/