numpy多维数组的条件运算

Aso*_*ile 5 python numpy multidimensional-array

我是一个天真的numpy用户,需要你的帮助以解决以下问题:我想用第三个数组替换多维数组的一些元素,这些元素少于第二个数组; 例如:

x = np.arange(16).reshape((2, 8)) 
# x = np.array([[ 0,  1,  2,  3,  4,  5,  6,  7],
#               [ 8,  9, 10, 11, 12, 13, 14, 15]])
Run Code Online (Sandbox Code Playgroud)

y = np.array([[2], [13]])
# y = np.array([[ 2], [13]])
Run Code Online (Sandbox Code Playgroud)

现在,找出x大于y,并且如果有至少一个Truex > y阵列中,计数这些实例中,创建另一阵列(z)和取代x与这些元素z:

x > y 
# = [[False, False, False, True,  True,  True,  True, True],
#    [False, False, False, False, False, False, True, True]]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,应该替换x(x[:,3:])的5个元素,因此我们创建一个(5, 2)数组:

z = np.array([[20,21],[22,23],[24,25],[26,27],[28,29]])
Run Code Online (Sandbox Code Playgroud)

我想要的结果是

x == np.array([[ 0,  1,  2, 20, 22, 24, 26, 28],
               [ 8,  9, 10, 21, 23, 25, 27, 29]])
Run Code Online (Sandbox Code Playgroud)

sen*_*rle 4

几乎完全符合您想要的numpy功能的函数是:numpy.where

x = np.arange(16).reshape((2, 8))
y = np.array([[2], [13]])
z = np.arange(16, 32).reshape((2, 8))
numpy.where(~(x > y).any(axis=0), x, z)
Run Code Online (Sandbox Code Playgroud)

结果:

array([[ 0,  1,  2, 19, 20, 21, 22, 23],
       [ 8,  9, 10, 27, 28, 29, 30, 31]])
Run Code Online (Sandbox Code Playgroud)

这与您所要求的唯一区别是它z必须可广播为与 相同的形状x。除非您绝对需要使用仅包含与中的值z一样多的列的值,否则我认为这是最好的方法。True~(x > y).any(axis=0)

但是,鉴于您的评论,您似乎确实需要使用z如上所述的值。听起来这个函数保证形状会匹配,所以你可以这样做:

x[:,(x > y).any(axis=0)] = z.T
Run Code Online (Sandbox Code Playgroud)

测试:

>>> z = np.arange(20, 30).reshape((5, 2))
>>> x[:,(x > y).any(axis=0)] = z.T
>>> x
array([[ 0,  1,  2, 20, 22, 24, 26, 28],
       [ 8,  9, 10, 21, 23, 25, 27, 29]])
Run Code Online (Sandbox Code Playgroud)