NumPy apply_over_axes()

apply_over_axes() 方法允许您跨多个轴重复应用一个函数。

示例

import numpy as np

# create a 3D array
arr = np.array([
    [[1, 2, 3],
     [4, 5, 6]],
    
    [[7, 8, 9],
     [10, 11, 12]]
])

# define a function to compute the column-wise sum
def col_sum(x, axis=0):
    # compute the sum along the specified axis
    return np.sum(x, axis=axis)

# apply col_sum over the first and third axes result = np.apply_over_axes(col_sum, arr, axes=(0, 2))
print(result) ''' Output: [[[ 8] [10] [12]] [[14] [16] [18]]] '''

apply_over_axes() 语法

apply_over_axes() 的语法是

numpy.apply_over_axes(func, array, axis)

apply_over_axes() 参数

apply_over_axes() 方法接受以下参数

  • func - 要应用的函数
  • axis - 函数应用的轴
  • array - 输入数组

注意: func 应接受两个参数,一个输入数组和一个轴。

apply_over_axes() 返回值

apply_over_axes() 方法返回应用函数后的结果数组。


示例 1:跨多个轴应用函数

import numpy as np

# create a 3D array
arr = np.arange(8).reshape(2, 2, 2)
print('Original Array:\n', arr)

# sum the array on axes (0 and 1) # adds the elements with same value at axis = 2 result = np.apply_over_axes(np.sum, arr, axes=(0, 1))
print('Sum along axes (0, 1):\n',result)
# sum the array on axes (0 and 2) # adds the elements with same value at axis = 1 result = np.apply_over_axes(np.sum, arr, axes=(0, 2))
print('Sum along axes (0, 2):\n',result)

输出

Original Array:
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
Sum along axes (0, 1):
 [[[12 16]]]
Sum along axes (0, 2):
 [[[10]
  [18]]]

示例 2:在数组中应用 lambda 函数

我们可以从函数返回一个值数组。

import numpy as np

# create a 2D array
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

# apply the lambda function to compute the sum of an array along a specific axis # compute the sum along the rows (axis=1) of the 2D array result = np.apply_over_axes(lambda arr, axis: np.sum(arr, axis=axis), arr, axes=(1))
print(result)

输出

[[ 6]
 [15]
 [24]]

推荐阅读

Numpy apply_along_axis()

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战