python - 根据复杂条件选择和重新分配数组中元素的最快方法

标签 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也许?

最佳答案

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

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/

相关文章:

python - 通过识别具有相同键但不同值的集合来比较 Python 中的两个字典

python - 处理 pandas 中按月分类的数据

python - 访问全息 View 中的 Bokeh (图形)参数

python - 带有权重的 numpy 数组部分和

c - 使用管道写入和读取 Int 数组

python - 使用神经网络根据用户输入预测结果

python - 矢量化 SVM 梯度

python - 将 python 源代码解析为 html - 引号

php - 为学生分配职位,PHP

python - 外积作为字符串?