gpt4 book ai didi

python - numpy 数组索引 : applying condition over the entire row/col

转载 作者:行者123 更新时间:2023-12-01 00:10:08 25 4
gpt4 key购买 nike

我有这个数组:

a=array([[0. , 0.3, 0.2],
[0.5, 0. , 0.1]])

以及这个自定义的 min 方法:

def custom_min(l_):
return min([x for x in l_ if x>0])

如何将其应用于行以选择其中的一些?例如,如果某行 custom_min > 0.1,则应选择该行:即

b = [[0. , 0.3, 0.2]]

要明确的是,我正在寻找这样的方法:

a[a[:,1] > 0.1]

最佳答案

首先,您可以使用 numpy.apply_along_axiscustom_min 应用于每一行。

我还会将 custom_min 重写为更加数字化:return min(l_[l_ > 0])

现在您在向量中拥有了自定义最小值,您可以再次使用逻辑索引:

row_mask = result > 0.3filtered_array = a[row_mask, :]

编辑:多思考一下如何让一切都只使用 numpy 向量化函数。我们可以首先使用 numpy.where 将所有小于 0 的值替换为无穷大。这就排除了最低限度的考虑:

row_wise_custom_mins = np.min(np.where(a > 0, a, np.inf), axis=1)

如果条件为 true,“where”将从 a 中选取值;如果条件为 false,则选取 np.inf。然后我们选择最小值(沿轴 1),就是这样。

关于python - numpy 数组索引 : applying condition over the entire row/col,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59689028/

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