杰瑞科技汇

Python中numpy.amax函数如何使用?

Of course! The numpy.amax function is a fundamental tool in the NumPy library for finding the maximum value in an array.

Python中numpy.amax函数如何使用?-图1
(图片来源网络,侵删)

Here's a complete guide covering what it is, how to use it, and its key features.

What is numpy.amax?

numpy.amax(a, axis=None, out=None, keepdims=False, initial=None, where=True)

The function numpy.amax (short for "array maximum") returns the maximum value of an array or along a specified axis.

  • In simple terms: It finds the biggest number in an array.
  • Key difference from numpy.max: numpy.amax is an alias for numpy.max. They are exactly the same function. You can use them interchangeably. amax was the original name, and max was added later for consistency with Python's built-in max() function. Most modern code uses np.max, but np.amax is still very common and perfectly valid.

Basic Usage (1-D Arrays)

This is the simplest case: finding the single maximum value in a flat array.

Python中numpy.amax函数如何使用?-图2
(图片来源网络,侵删)
import numpy as np
# Create a 1D array
arr_1d = np.array([10, 5, 25, 8, 30, 2])
# Find the maximum value
max_value = np.amax(arr_1d)
print(f"Array: {arr_1d}")
print(f"Maximum value (np.amax): {max_value}")

Output:

Array: [10  5 25  8 30  2]
Maximum value (np.amax): 30

Finding Maximum Along an Axis (2-D and N-D Arrays)

This is where np.amax becomes incredibly powerful. You can specify the axis argument to find the maximum along rows or columns.

axis=0: Maximum along Columns

When axis=0, the function operates column-wise. It collapses the rows, finding the maximum value in each column.

import numpy as np
# Create a 2D array (3 rows, 4 columns)
arr_2d = np.array([
    [1, 5, 9, 13],
    [2, 6, 10, 14],
    [3, 7, 11, 15]
])
# Find the maximum along axis=0 (columns)
max_along_columns = np.amax(arr_2d, axis=0)
print(f"Original Array:\n{arr_2d}\n")
print(f"Shape of original array: {arr_2d.shape}")
print(f"Maximum along axis=0 (columns): {max_along_columns}")
print(f"Shape of result: {max_along_columns.shape}")

Explanation:

  • Column 0: max(1, 2, 3) = 3
  • Column 1: max(5, 6, 7) = 7
  • Column 2: max(9, 10, 11) = 11
  • Column 3: max(13, 14, 15) = 15

Output:

Original Array:
[[ 1  5  9 13]
 [ 2  6 10 14]
 [ 3  7 11 15]]
Maximum along axis=0 (columns): [ 3  7 11 15]
Shape of result: (4,)

axis=1: Maximum along Rows

When axis=1, the function operates row-wise. It collapses the columns, finding the maximum value in each row.

import numpy as np
# Use the same 2D array
arr_2d = np.array([
    [1, 5, 9, 13],
    [2, 6, 10, 14],
    [3, 7, 11, 15]
])
# Find the maximum along axis=1 (rows)
max_along_rows = np.amax(arr_2d, axis=1)
print(f"Original Array:\n{arr_2d}\n")
print(f"Shape of original array: {arr_2d.shape}")
print(f"Maximum along axis=1 (rows): {max_along_rows}")
print(f"Shape of result: {max_along_rows.shape}")

Explanation:

  • Row 0: max(1, 5, 9, 13) = 13
  • Row 1: max(2, 6, 10, 14) = 14
  • Row 2: max(3, 7, 11, 15) = 15

Output:

Original Array:
[[ 1  5  9 13]
 [ 2  6 10 14]
 [ 3  7 11 15]]
Maximum along axis=1 (rows): [13 14 15]
Shape of result: (3,)

Important Optional Parameters

keepdims=True

By default, when you use axis, the dimension you're operating over is removed. keepdims=True preserves the original number of dimensions in the output array, which is often useful for broadcasting or further calculations.

import numpy as np
arr_2d = np.array([
    [1, 5, 9],
    [2, 6, 10]
])
# Default behavior (axis is squeezed out)
max_default = np.amax(arr_2d, axis=1)
print(f"Default result (shape): {max_default.shape}") # Output: (2,)
# With keepdims=True
max_keepdims = np.amax(arr_2d, axis=1, keepdims=True)
print(f"With keepdims=True (shape): {max_keepdims.shape}") # Output: (2, 1)
print(f"\nResult with keepdims:\n{max_keepdims}")

Output:

Default result (shape): (2,)
With keepdims=True (shape): (2, 1)
Result with keepdims:
[[ 9]
 [10]]

initial=

This parameter is useful if you want to find the maximum value but have a guaranteed starting value. For example, if all numbers in your array are negative, initial=0 will correctly return 0 as the maximum.

import numpy as np
# An array with all negative numbers
arr_negative = np.array([-10, -5, -2, -50])
# Without initial, the max is -2
print(f"Max without initial: {np.amax(arr_negative)}")
# With initial=0, the max is 0
print(f"Max with initial=0: {np.amax(arr_negative, initial=0)}")

Output:

Max without initial: -2
Max with initial=0: 0

where=

This is a powerful feature for conditional maximums. It allows you to specify a boolean mask. The maximum will only be calculated over elements where the where condition is True.

import numpy as np
arr = np.array([1, 8, 3, 9, 5, 7])
# We only want to consider elements that are even
# The mask is: [False, True, False, True, False, True]
max_even = np.amax(arr, where=(arr % 2 == 0))
print(f"Array: {arr}")
print(f"Maximum value among even numbers: {max_even}")
# NOTE: If no elements satisfy the condition, the default behavior is to
# raise an error. You should often use 'initial' with 'where'.
arr_all_odd = np.array([1, 3, 5])
try:
    np.amax(arr_all_odd, where=(arr_all_odd % 2 == 0))
except ValueError as e:
    print(f"\nError with all-odd array: {e}")
# To fix this, provide an initial value
max_even_safe = np.amax(arr_all_odd, where=(arr_all_odd % 2 == 0), initial=-1)
print(f"Safe maximum with initial=-1: {max_even_safe}")

Output:

Array: [1 8 3 9 5 7]
Maximum value among even numbers: 8
Error with all-odd array: zero-size array to reduction operation maximum which has no identity
Safe maximum with initial=-1: -1

np.amax vs. np.max vs. arr.max()

As mentioned, np.amax and np.max are identical. The third option, arr.max(), is a method on the NumPy array object. It is also identical in functionality.

import numpy as np
arr = np.array([10, 50, 20, 80, 30])
# All three produce the exact same result
amax_val = np.amax(arr)
max_val = np.max(arr)
method_val = arr.max()
print(f"np.amax(arr): {amax_val}")
print(f"np.max(arr): {max_val}")
print(f"arr.max():    {method_val}")
# They are the same function
print(f"\nnp.amax is np.max: {np.amax is np.max}")

Which one to use?

  • np.max(arr) is arguably the most readable and "Pythonic" choice.
  • arr.max() is also very common and convenient if you already have the array in a variable.
  • np.amax(arr) is perfectly fine and widely used, especially in older codebases. It's the shortest to type.

Summary Table

Feature Description Example
Purpose Find the maximum value in an array. np.amax([1, 5, 3]) -> 5
axis Specifies the axis along which to find the max. np.amax(matrix, axis=0) (column-wise max)
keepdims If True, keeps the reduced axis as a dimension of size 1. np.amax(matrix, axis=1, keepdims=True)
initial Provides a starting value for the maximum calculation. Useful for empty arrays or with where. np.amax(arr, initial=0)
where Specifies a boolean mask to include only certain elements in the calculation. np.amax(arr, where=(arr > 5))
np.amax vs np.max They are identical aliases. np.amax is np.max
arr.max() A method on the array object, identical in functionality to the functions. my_array.max()
分享:
扫描分享到社交APP
上一篇
下一篇