python - 我如何在 numpy 中向量化这个循环?

标签 python numpy

我有这个数组:

arr = np.array([3, 7, 4])

还有这些 bool 索引:

cond = np.array([False, True, True])

我想在 bool 条件为真的数组中找到最大值的索引。所以我这样做:

np.ma.array(arr, mask=~cond).argmax()

有效并返回 1。但是如果我有一个 bool 索引数组:

cond = np.array([[False, True, True], [True, False, True]])

是否有一种向量化/numpy 的方法来遍历 bool 索引数组以返回 [1, 2]?

最佳答案

对于 argmax 的特殊用例,您可以使用 np.where并将掩码值设置为负无穷大:

>>> inf = np.iinfo('i8').max
>>> np.where(cond, arr, -inf).argmax(axis=1)
array([1, 2])

或者,您可以使用 np.tile 手动广播:

>>> np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)
array([1, 2])

关于python - 我如何在 numpy 中向量化这个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31767173/

相关文章:

python - $ python -c "script"中的反斜杠

python - 带连字符的正则表达式单词

python - 根据指数分布生成数据

python - Groupby 与 TimeGrouper 'backwards'

python - 在 Python Numba/NumPy 中实现的分摊 O(1) 滚动最小值

python - OpenCV createCalibrateDebevec.process 给我 "dst is not a numpy array, neither a scalar"

python - 在python中将.txt文件转换为整数矩阵

python - 如何通过索引获取双端队列元素?

python - "pandas datetime convert to num"中的问题

python - 如何使用 google docs api (Python) 更新 google doc