1

Say I have, as an arbitrary example, two 2d numpy arrays, X and Y where

    X = np.array([[0,1,2,3],
                  [4,5,6,7]]) 
    Y = np.array([[1,2,3,4],
                  [1,1,7,3]])

I want to create a new 2d numpy array, Z, that is the argmax of X,Y element-wise so Z would be, in this example:

    Z = np.array([[1,2,3,4],
                  [4,5,7,7]])

I've tried variations of the following none return the intended result

    np.array([(np.argmax(X,Y))]) --> error

I know I can do this simply by using a nested for loop but that isn't very efficient for very large datasets. Is there an efficient, numpy-specific, way to create a new 2d array (Z, in the example above) composed of the argmax by element from two 2d arrays (X and Y, in the example above)?

Zuckerbrenner
  • 323
  • 2
  • 15

2 Answers2

2

You're looking for np.maximum:

>>> np.maximum(X, Y)

array([[1, 2, 3, 4],
       [4, 5, 7, 7]])

which compares the arrays element-wise and returns the maximum for each of them.

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
1

Use numpy.where:

Z = np.where(X > Y, X, Y)

Here, the first argument X > Y compares X and Y element by element, and returns a boolean array of the comparison. Then we use the boolean array to build Z: if the element at an index is True, it uses the value from X, and if it is False it uses the value from Y.

Kraigolas
  • 5,121
  • 3
  • 12
  • 37