gpt4 book ai didi

python - 追溯 bool 掩码 NumPy 数组上 argmin/argmax 的原始位置 - Python

转载 作者:行者123 更新时间:2023-12-01 00:40:24 28 4
gpt4 key购买 nike

上下文

由于使用 numpy.ma 模块进行掩码比直接 bool 掩码慢得多,因此我必须将后者用于我的 argmin/argmax-计算。

一点比较:

import numpy as np

# Masked Array
arr1 = np.ma.masked_array([12,4124,124,15,15], mask=[0,1,1,0,1])

# Boolean masking
arr2 = np.array([12,4124,124,15,15])
mask = np.array([0,1,1,0,1], dtype=np.bool)

%timeit arr1.argmin()
# 16.1 µs ± 4.88 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit arr2[mask].argmin()
# 946 ns ± 55.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

无论如何,使用argmin/argmax返回数组中第一个匹配项的索引。在 bool 掩码的情况下,这意味着 arr2[mask] 中的索引,而不是 arr2 中。我的问题是:在对屏蔽数组进行计算时,我需要未屏蔽数组中的索引


问题

如何获取未屏蔽的 arr2argmin/argmax 索引,即使我将其应用于 bool 值屏蔽版本arr2[mask]

最佳答案

这是一个主要基于masking的方法,特别是-mask-the-mask,并且应该具有内存效率,并且希望性能也很好,特别是在处理大型数组时-

def reset_first_n_True(mask, n):
# Resets (fills with False) first n True places in mask

# Count of True in original mask array
c = np.count_nonzero(mask)

# Setup second mask that is to be assigned into original mask on its
# own True positions with the idea of setting first argmin_in_masked_ar
# True values to False
second_mask = np.ones(c, dtype=bool)
second_mask[:n] = False
mask[mask] = second_mask
return

# Use reduction function on masked data array
idx = np.argmin(random_array[random_mask])
reset_first_n_True(random_mask, idx)
out = random_mask.argmax()

要获取屏蔽数据数组上的 argmax 并将其追溯到原始位置,只需更改第一步以包含该内容:

idx = np.argmax(random_array[random_mask])

因此,可以使用任何归约操作并以这种方式追溯到它们的原始位置。

<小时/>

如果您正在寻找紧凑的解决方案,请使用nonzero() -

idx = np.flatnonzero(random_mask)
out = idx[random_array[random_mask].argmin()]
# Or idx[random_array[idx].argmin()]

关于python - 追溯 bool 掩码 NumPy 数组上 argmin/argmax 的原始位置 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57391453/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com