使用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))
輸出
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
廣告