在 Numpy 中降低数组维度并使用不同的值初始化降维
要将数组的维度降低一个维度,请在 Python Numpy 中使用 **np.ufunc.reduce()** 方法。在这里,我们使用了 **add.reduce()** 将其简化为所有元素的总和。要使用不同的值初始化降维,请使用“initials”参数。
通用函数(简称 ufunc)是在元素级对 ndarray 进行运算的函数,支持数组广播、类型转换以及其他一些标准功能。也就是说,ufunc 是对一个函数的“矢量化”包装,该函数需要固定数量的特定输入并产生固定数量的特定输出。
步骤
首先,导入所需的库 -
import numpy as np
创建一个一维数组 -
arr = np.array([7, 14, 21, 28, 35])
显示数组 -
print("Array...
", arr)获取数组的类型 -
print("
Our Array type...
", arr.dtype)
获取数组的维度 -
print("
Our Array Dimensions...
",arr.ndim)要将数组的维度降低一个维度,请在 Python Numpy 中使用 np.ufunc.reduce() 方法。在这里,我们使用了 add.reduce() 将其简化为所有元素的总和。要使用不同的值初始化降维,请使用“initials”参数 -
print("
Result (addition)...
",np.add.reduce(arr, initial = 99))
示例
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([7, 14, 21, 28, 35])
# 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 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
# To initialize the reduction with a different value, use the "initials" parameter
print("
Result (addition)...
",np.add.reduce(arr, initial = 99))输出
Array... [ 7 14 21 28 35] Our Array type... int64 Our Array Dimensions... 1 Result (addition)... 204
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP