Python amin中的条件句

Python amin中的条件句,python,numpy,conditional,min,Python,Numpy,Conditional,Min,我有两个数组U和V,它们都是形状(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

我有两个数组
U
V
,它们都是形状(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)结构,并使搜索列式最小值变得不可能(显然)


是否有一种方法可以修改此代码,以便返回所需的列式最小值?

可能不是最漂亮的解决方案,但它很有效;-)

mask=np.where(V[:,:]<0,np.inf,1)
x=np.amin(U*掩模,轴=1)

可能不是最漂亮的解决方案,但它很有效;-)

mask=np.where(V[:,:]<0,np.inf,1)
x=np.amin(U*掩模,轴=1)

这听起来像是一项任务:


这听起来像是一项任务:


您可以将
where
iinfo
一起使用:

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)

您可以将
where
iinfo
一起使用:

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)

谢谢,感谢定量比较!谢谢,感谢定量比较!
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)