Related Tags

numpy
python
communitycreator

# Find the maximum value in each row and column of a NumPy 2D array

Harsh Jain

In this shot we will discuss on how to find the maximum value across each row and each column in a NumPy 2D array.

### Introduction

To solve the problem mentioned above, we will use amax() method from the numpy python package.

The amax() method is used to find the maximum value across the axis or in a given 1D array. Below is the syntax to use the method:

numpy.amax(array, axis);


Let us see the code to implement the solution to find the maximum value across each row and each column.

import numpy as np

numpy_oned_array = np.array([1, 2, -4, 10, -11, 4, 22])

max_value_oned = np.amax(numpy_oned_array)
print("Maximum value in the array: ", max_value_oned)

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

max_value_twod_row = np.amax(numpy_twod_array, axis = 1)
max_value_twod_col = np.amax(numpy_twod_array, axis = 0)

print("Row wise maximum: ", max_value_twod_row)
print("Column wise maximum: ", max_value_twod_col)
Find the maximum value in each row and column of a NumPy 2D array

### Explanation

• In line 1, we import the required package.

• In line 3, we define a numpy 1D array.

• In line 5, we use the amax() method to find the maximum value in the array. Then, we print the maximum value in line 6.

• From lines 8 to 12, we define a numpy 2D array.

• In lines 14 and 15, we use the amax() method to find the maximum across the row and column respectively. Note that, here we passed the value of axis to be either 0 (denoting the column wise maximum) or 1 (denoting the row wise maximum).

• Finally, in lines 17 and 18, we print the maximum values.

RELATED TAGS

numpy
python
communitycreator

CONTRIBUTOR

Harsh Jain
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time