In NumPy, max()
is a method used to find the maximum value in an array. It can work on the entire array or along a specific axis (row or column). This method is useful when you need to identify the highest number in a dataset or perform data analysis operations.
Contents
Example
import numpy as np
arr = np.array([1, 5, 8, 3])
print(np.max(arr)) # 8
What it does
np.max()
scans through the elements of an array and returns the largest one. You can also use it to find the maximum value along a specific dimension (row or column) in a multi-dimensional array.
- Overall maximum: By default,
np.max()
returns the highest value in the entire array. - Axis-specific: You can specify an axis to find the maximum along rows or columns in 2D arrays.
Examples
Example 1: Finding the maximum in a 1D array
import numpy as np
arr = np.array([3, 7, 2, 9, 5])
print(np.max(arr)) # 9
Here, np.max()
scans through the array [3, 7, 2, 9, 5]
and returns 9
since it’s the largest number in this 1D array.
Example 2: Finding the maximum in a 2D array
import numpy as np
matrix = np.array([[1, 5, 3],
[7, 2, 8],
[4, 6, 0]])
print(np.max(matrix)) # 8
When used on a 2D array, np.max()
returns the highest value from all elements in the array. In this case, it returns 8
as it’s the largest value in the matrix.
Example 3: Finding the maximum along a specific axis
import numpy as np
matrix = np.array([[2, 9, 4],
[6, 1, 8],
[3, 5, 7]])
print(np.max(matrix, axis=0)) # [6 9 8]
print(np.max(matrix, axis=1)) # [9 8 7]
- When specifying
axis=0
,np.max()
finds the maximum values for each column, returning[6, 9, 8]
. - When specifying
axis=1
, it finds the maximum values for each row, returning[9, 8, 7]
.
Example 4: Finding the maximum with NaN values
import numpy as np
arr = np.array([3, np.nan, 7, 2])
print(np.nanmax(arr)) # 7
If your array contains NaN
values, use np.nanmax()
to find the maximum while ignoring NaN
. Here, it returns 7
, ignoring the NaN
value.