NumPy 中多維陣列的降維與元素相乘
要縮減多維陣列,請在 Python NumPy 中使用 **np.ufunc.reduce()** 方法。這裡,我們使用了 **multiply.reduce()** 將其縮減為元素的乘積。
通用函式(簡稱 ufunc)是在元素級對 ndarray 進行操作的函式,支援陣列廣播、型別轉換和一些其他標準特性。也就是說,ufunc 是對接收固定數量的特定輸入並生成固定數量的特定輸出的函式的“向量化”封裝。numpy.ufunc 具有對整個陣列逐元素操作的函式。ufunc 使用 C 語言編寫(為了速度),並透過 NumPy 的 ufunc 功能連結到 Python。
步驟
首先,匯入所需的庫 -
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() 將其縮減為元素的乘積 -
print("
Result (multiply)...
",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 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
print("
Result (multiply)...
",np.multiply.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 (multiply)... [[ 0 190 440] [ 756 1144 1610] [2160 2800 3536]]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP