在 Numpy 中沿负轴减少多维数组
要沿负轴减少多维数组,请在 Python Numpy 中使用 **np.ufunc.reduce()** 方法。这里,我们使用 **add.reduce()** 将其减少到元素的加法。轴使用“axis”参数设置。执行缩减的轴或轴。
**numpy.ufunc** 具有逐元素对整个数组进行运算的函数。ufunc是用 C 编写的(为了速度)并与 NumPy 的 ufunc 功能链接到 Python。通用函数(或简称 ufunc)是逐元素对 ndarrays 进行运算的函数,支持数组广播、类型转换和几个其他标准功能。也就是说,ufunc 是一个“矢量化”的函数包装器,它接受固定数量的特定输入并产生固定数量的特定输出。
步骤
首先,导入所需的库 -
import numpy as np
创建一个多维数组 -
arr = np.arange(27).reshape((3,3,3))
显示数组 -
print("Array...
", arr)
获取数组的类型 -
print("
Our Array type...
", arr.dtype)
获取数组的维度 -
print("
Our Array Dimensions...
",arr.ndim)
要减少多维数组,请在 Python Numpy 中使用 np.ufunc.reduce() 方法。这里,我们使用 multiply.reduce() 将其减少到元素的乘法。轴使用“axis”参数设置。执行缩减的轴或轴。负轴从最后一个轴到第一个轴进行计数 -
print("
Result (multiplication)...
",np.multiply.reduce(arr, axis = -1))
要减少多维数组,请在 Python Numpy 中使用 np.ufunc.reduce() 方法。这里,我们使用 add.reduce() 将其减少到元素的加法。轴使用“axis”参数设置。执行缩减的轴或轴。负轴从最后一个轴到第一个轴进行计数 -
print("
Result (addition)...
",np.add.reduce(arr, axis = -1))
示例
import numpy as np # The numpy.ufunc has functions that operate element by element on whole arrays. # ufuncs are written in C (for speed) and linked into Python with NumPy’s ufunc facility # Create a multi-dimensional array arr = np.arange(27).reshape((3,3,3)) # Display the array print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimensions...
",arr.ndim) # To reduce a multi-dimensional array, use the np.ufunc.reduce() method in Python Numpy # Here, we have used multiply.reduce() to reduce it to the multiplication of elements elements # The axis is set using the "axis" parameter # Axis or axes along which a reduction is performed # The negative axis it counts from the last to the first axis. print("
Result (multiplication)...
",np.multiply.reduce(arr, axis = -1)) # To reduce a multi-dimensional array, use the np.ufunc.reduce() method in Python Numpy # Here, we have used add.reduce() to reduce it to the addition of elements # The axis is set using the "axis" parameter # Axis or axes along which a reduction is performed # The negative axis counts from the last to the first axis. print("
Result (addition)...
",np.add.reduce(arr, axis = -1))
输出
Array... [[[ 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]]] Our Array type... int64 Our Array Dimensions... 3 Result (multiplication)... [[ 0 60 336] [ 990 2184 4080] [ 6840 10626 15600]] Result (addition)... [[ 3 12 21] [30 39 48] [57 66 75]]
广告