NumPy中多维数组的降维和元素相加


要减少多维数组,请在Python NumPy中使用**np.ufunc.reduce()**方法。在这里,我们使用**add.reduce()**将其简化为元素的加法。

**numpy.ufunc**具有逐元素操作整个数组的函数。ufunc是用C语言编写的(为了速度),并使用NumPy的ufunc工具链接到Python。通用函数(简称ufunc)是在逐元素的基础上操作ndarray的函数,支持数组广播、类型转换以及其他一些标准功能。也就是说,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()方法。在这里,我们使用add.reduce()将其简化为元素的加法:

print("
Result (addition)...
",np.add.reduce(arr))

示例

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 add.reduce() to reduce it to the addition of elements print("
Result (addition)...
",np.add.reduce(arr))

输出

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 (addition)...
[[27 30 33]
[36 39 42]
[45 48 51]]

更新于:2022年2月7日

416 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.