在 Numpy 中缩减多维数组并沿负轴添加元素

numpyserver side programmingprogramming更新于 2025/9/3 4:37:17

要缩减多维数组,请使用 Python Numpy 中的 np.ufunc.reduce() 方法。这里我们使用了 multiply.reduce() 将其缩减为元素的乘法。轴使用"axis"参数设置。缩减操作沿一个或多个轴进行。负轴从最后一个轴计数到第一个轴。

通用函数(简称 ufunc)是一种以逐个元素的方式对 ndarray 进行操作的函数,支持数组广播、类型转换和其他一些标准特性。也就是说,ufunc 是一个"向量化"的函数包装器,它接受固定数量的特定输入并产生固定数量的特定输出。

步骤

首先,导入所需的库 −

import numpy as np

创建多维数组−

arr = np.arange(27).reshape((3,3,3))

显示数组 −

print("数组...
", arr)

获取数组的类型 −

print("
我们的数组类型...
", arr.dtype)

获取数组的维度 −

print("
我们的数组维度...
",arr.ndim)

要简化多维数组,请使用 Python Numpy 中的 np.ufunc.reduce() 方法。这里我们使用 multiply.reduce() 将其简化为元素的乘法。使用"axis"参数设置轴。执行缩减的轴. The negative axis counts from the last to the first axis −

print("
沿特定轴的结果(乘法)...
",np.multiply.reduce(arr, axis = -1))

示例

import numpy as np

# numpy.ufunc 函数可以对整个数组逐个元素进行操作。
# ufunc 函数用 C 语言编写(以提高速度),并通过 NumPy 的 ufunc 功能链接到 Python。

# 创建多维数组
arr = np.arange(27).reshape((3,3,3))

# 显示数组
print("数组...
", arr) # 获取数组的类型 print("
我们的数组类型...
", arr.dtype) # 获取数组的维度 print("
我们的数组维度...
",arr.ndim) # 要对多维数组进行归约,请使用 Python Numpy 中的 np.ufunc.reduce() 方法 # 这里我们使用 multiply.reduce() 将其归约成元素的乘法 # 使用"axis"参数设置轴 # 执行归约的轴 # 负轴从最后一个轴计数到第一个轴 print("
沿特定轴的结果(乘法)...
",np.multiply.reduce(arr, axis = -1))

输出

数组...
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]

[[ 9 10 11]
[12 13 14]
[15 16 17]]

[[18 19 20]
[21 22 23]
[24 25 26]]]

我们的数组类型...
int64

我们的数组维度...
3

沿特定轴的结果(乘法)...
[[ 0 60 336]
[ 990 2184 4080]
[ 6840 10626 15600]]

相关文章