在 NumPy 中將 ufunc outer() 函式應用於一維陣列的所有配對


我們將 ufunc outer() 函式應用於一維陣列的所有配對。numpy.ufunc 包含對整個陣列逐元素進行操作的函式。ufunc是用 C 語言編寫的(為了提高速度),並透過 NumPy 的 ufunc 功能連結到 Python 中。

通用函式(簡稱 ufunc)是一種以逐元素方式對 ndarray 進行操作的函式,支援陣列廣播、型別轉換和許多其他標準功能。也就是說,ufunc 是對一個函式的“向量化”包裝器,該函式接受固定數量的特定輸入併產生固定數量的特定輸出。

步驟

首先,匯入所需的庫 -

import numpy as np

numpy.ufunc 包含對整個陣列逐元素進行操作的函式。ufunc是用 C 語言編寫的(為了提高速度),並透過 NumPy 的 ufunc 功能連結到 Python 中 -

建立兩個一維陣列 -

arr1 = np.array([5, 10, 15, 20, 25, 30, 35, 40])
arr2 = np.array([7, 14, 21, 28, 35])

顯示陣列 -

print("Array 1...
", arr1) print("
Array 2...
", arr2)

獲取陣列的型別 -

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

獲取陣列的維度 -

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

獲取陣列的形狀 -

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

將 ufunc outer() 函式應用於所有 1D 陣列對 -

res = np.multiply.outer(arr1, arr2)
print("
Result...
",res) print("
Shape...
",res.shape)

示例

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 two 1D arrays
arr1 = np.array([5, 10, 15, 20, 25, 30, 35, 40])
arr2 = np.array([7, 14, 21, 28, 35])

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # Apply the ufunc outer() function to all pairs of 1D arrays res = np.multiply.outer(arr1, arr2) print("
Result...
",res) print("
Shape...
",res.shape)

輸出

Array 1...
[ 5 10 15 20 25 30 35 40]

Array 2...
[ 7 14 21 28 35]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(8,)

Our Array 2 Shape...
(5,)

Result...
[[ 35 70 105 140 175]
[ 70 140 210 280 350]
[ 105 210 315 420 525]
[ 140 280 420 560 700]
[ 175 350 525 700 875]
[ 210 420 630 840 1050]
[ 245 490 735 980 1225]
[ 280 560 840 1120 1400]]

Shape...
(8, 5)

更新於: 2022-02-07

101 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.