NumPy中沿軸1約簡多維陣列
要約簡多維陣列,請使用Python NumPy中的**np.ufunc.reduce()**方法。這裡,我們使用**add.reduce()**將其約簡為元素的加法。軸使用“axis”引數設定。沿其執行約簡的軸。
**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()方法。這裡,我們使用multiply.reduce()將其約簡為元素的乘法。軸使用“axis”引數設定。沿其執行約簡的軸。
print("
Result (multiplication)...
",np.multiply.reduce(arr, axis = 1))要約簡多維陣列,請使用Python NumPy中的np.ufunc.reduce()方法。這裡,我們使用add.reduce()將其約簡為元素的加法。軸使用“axis”引數設定。沿其執行約簡的軸:
print("
Result (addition)...
",np.add.reduce(arr, axis = 1))示例
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 elements
# The axis is set using the "axis" parameter
# Axis or axes along which a reduction is performed
print("
Result (multiplication)...
",np.multiply.reduce(arr, axis = 1))
# 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
# The axis is set using the "axis" parameter
# Axis or axes along which a reduction is performed
print("
Result (addition)...
",np.add.reduce(arr, axis = 1))輸出
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 (multiplication)... [[ 0 28 80] [ 1620 2080 2618] [ 9072 10450 11960]] Result (addition)... [[ 9 12 15] [36 39 42] [63 66 69]]
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP