gpt4 book ai didi

python - amin 中的条件

转载 作者:太空宇宙 更新时间:2023-11-04 07:15:15 24 4
gpt4 key购买 nike

我有两个数组 UV,都是形状 (f, m)。我将在下面的示例中设置 f = 4,m = 3。

我想提取U每一列的最小值,前提是V中相应的值是非负的,即对于第j^列,我想要返回 U[i,j] 的最小值,使得 V[i,j] > 0

我的第一次尝试是:

import numpy as np

U = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
V = np.array([[1,-1,1],[1,1,1],[-1,-1,1],[-1,-1,1]])

mask = (V > 0)

np.amin(U[mask], axis = 0)

但是这会返回 1(整个数组的最小值),而不是 [1,5,3],这是我正在寻找的有条件的按列的最小值。

我的问题似乎是 U[mask] 变平为形状 (1, 7),这破坏了 (4, 3) 结构,并使得搜索列最小值不可能(显然)。

我有没有办法修改这段代码,以便我可以返回我正在寻找的列最小值?

最佳答案

您可以将 whereiinfo 一起使用:

np.where(V>0, U, np.iinfo(int).max).min(axis=0)
# array([1, 5, 3], dtype=int64)

np.inf 不是整数,因此会强制执行不需要的向上转换。

np.where(V>0, U, np.inf).min(axis=0)
# array([1., 5., 3.])

一步一步:

np.iinfo(int)
# iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)

np.where(V>0, U, np.iinfo(int).max)
# array([[ 1, 9223372036854775807, 3],
# [ 4, 5, 6],
# [9223372036854775807, 9223372036854775807, 9],
# [9223372036854775807, 9223372036854775807, 12]],
# dtype=int64)

关于python - amin 中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49554747/

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