使用Numpy减少数组维度:将所有元素相乘
要将数组的维度减少一维,请在 Python Numpy 中使用 **np.ufunc.reduce()** 方法。这里我们使用了 **multiply.reduce()** 将其简化为所有元素的乘积。
numpy.ufunc 包含逐元素操作整个数组的函数。ufunc 使用 C 语言编写(为了速度),并通过 NumPy 的 ufunc 功能链接到 Python。通用函数(简称 ufunc)是在逐元素方式操作 ndarray 的函数,支持数组广播、类型转换和几个其他标准功能。也就是说,ufunc 是对函数的“矢量化”包装器,该函数接受固定数量的特定输入并产生固定数量的特定输出。
步骤
首先,导入所需的库:
import numpy as np
创建一个一维数组:
arr = np.array([3, 4, 6, 1, 7, 9])
显示数组:
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() 方法。这里我们使用了 multiply.reduce() 将其简化为所有元素的乘积:
print("Result (multiplication)...",np.multiply.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([3, 4, 6, 1, 7, 9]) # 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 multiply.reduce() to reduce it to the multiplication of all the elements print("Result (multiplication)...",np.multiply.reduce(arr))
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Array... [3 4 6 1 7 9] Our Array type... int64 Our Array Dimensions... 1 Our Array Shape... (6,) Number of elements... 6 Result (multiplication)... 4536
广告