在 Numpy 中將陣列的維度降低一位


要將陣列的維度降低一位,請在 Python Numpy 中使用 **np.ufunc.reduce()** 方法。在這裡,我們使用 **multiply.reduce()** 將其縮減為所有元素的乘積。

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

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個一維陣列 -

arr = np.array([7, 14, 21, 28, 35])

顯示陣列 -

print("Array...
", arr)

獲取陣列的型別 -

print("
Our Array type...
", arr.dtype)

獲取陣列的維度 -

print("
Our Array Dimensions...
",arr.ndim)

要將陣列的維度降低一位,請在 Python Numpy 中使用 np.ufunc.reduce() 方法。在這裡,我們使用 multiply.reduce() 將其縮減為所有元素的乘積 -

print("
Result (multiplication)...
",np.multiply.reduce(arr))

要將陣列的維度降低一位,請在 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([7, 14, 21, 28, 35])

# 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 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)) # 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...
[ 7 14 21 28 35]

Our Array type...
int64

Our Array Dimensions...
1

Result (addition)...
105

更新於: 2022 年 2 月 7 日

785 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告