使用Numpy减少数组维度,将所有元素相加


要将数组的维度减少一个,可以使用 Python Numpy 中的 **np.ufunc.reduce()** 方法。在这里,我们使用了 **add.reduce()** 将其简化为所有元素的加和。

numpy.ufunc 包含对整个数组逐元素操作的函数。ufunc是用C语言编写的(为了速度),并通过NumPy的ufunc功能链接到Python。通用函数(或简称ufunc)是在元素级对ndarray进行操作的函数,支持数组广播、类型转换和一些其他标准特性。也就是说,ufunc是“矢量化”的函数包装器,它接受固定数量的特定输入并产生固定数量的特定输出。

步骤

首先,导入所需的库 -

import numpy as np

创建一个一维数组 -

arr = np.array([11, 31, 42, 56, 61, 70, 77, 92])

显示数组 -

print("Array...
", arr)

获取数组的类型 -

print("
Our Array type...
", arr.dtype)

获取数组的维度 -

print("
Our Array Dimensions...
",arr.ndim)

获取数组的形状 -

print("
Our Array Shape...
",arr.shape)

获取数组的元素个数 -

print("
Number of elements...
",arr.size)

要将数组的维度减少一个,可以使用 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 1D array
arr = np.array([11, 31, 42, 56, 61, 70, 77, 92])

# 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) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the count of elements of the Array print("
Number of elements...
",arr.size) # To reduce array’s dimension by one, use the np.ufunc.reduce() method in Python Numpy # Here, we have used add.reduce() to reduce it to the addition of all the elements print("
Result (addition)...
",np.add.reduce(arr))

输出

Array...
[11 31 42 56 61 70 77 92]

Our Array type...
int64

Our Array Dimensions...
1

Our Array Shape...
(8,)

Number of elements...
8

Result (addition)...
440

更新于: 2022年2月7日

172 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.