使用Numpy減少陣列維度,將所有元素相加


要將陣列的維度減少一個,可以使用 Python Numpy 中的 **np.ufunc.reduce()** 方法。在這裡,我們使用了 **add.reduce()** 將其簡化為所有元素的加和。

numpy.ufunc 包含對整個陣列逐元素操作的函式。ufunc是用C語言編寫的(為了速度),並透過NumPy的ufunc功能連結到Python。通用函式(或簡稱ufunc)是在元素級對ndarray進行操作的函式,支援陣列廣播、型別轉換和一些其他標準特性。也就是說,ufunc是“向量化”的函式包裝器,它接受固定數量的特定輸入併產生固定數量的特定輸出。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個一維陣列 -

arr = np.array([11, 31, 42, 56, 61, 70, 77, 92])

顯示陣列 -

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() 方法。在這裡,我們使用了 add.reduce() 將其簡化為所有元素的加和 -

print("
Result (addition)...
",np.add.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([11, 31, 42, 56, 61, 70, 77, 92])

# 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 add.reduce() to reduce it to the addition of all the elements print("
Result (addition)...
",np.add.reduce(arr))

輸出

Array...
[11 31 42 56 61 70 77 92]

Our Array type...
int64

Our Array Dimensions...
1

Our Array Shape...
(8,)

Number of elements...
8

Result (addition)...
440

更新於: 2022年2月7日

172 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.