Conditional operation on numpy multidimensional array

I am a naive user with a zero value, you need your help for the following problem: I want to replace some elements of a multidimensional array that are smaller than the second array with a third array; eg:.

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]])

and

y = np.array([[2], [13]])
# y = np.array([[ 2], [13]])

Now find out where xmore than y, and if x > ythere is at least one Truearray in the array, count these instances, create another array ( z) and replace x> in these elements with z:

x > y 
# = [[False, False, False, True,  True,  True,  True, True],
#    [False, False, False, False, False, False, True, True]]

In this case, it is necessary to replace 5 elements x( x[:,3:]), so we create an array (5, 2):

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

As a result i want

x == np.array([[ 0,  1,  2, 20, 22, 24, 26, 28],
               [ 8,  9, 10, 21, 23, 25, 27, 29]])
+5
source share
1 answer
Function

A 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)

:

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

, , , z , x. z , True ~(x > y).any(axis=0), , .

, , , z, . , , , :

x[:,(x > y).any(axis=0)] = z.T

:

>>> 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]])
+4

All Articles