在 Python 中獲取陣列與字母向量的外積


給定兩個向量,a = [a0, a1, ..., aM] 和 b = [b0, b1, ..., bN],外積為 -

[[a0*b0 a0*b1 ... a0*bN ]
[a1*b0 .
[ ... .
[aM*b0     aM*bN ]]

要獲取陣列與字母向量的外積,請在 Python 中使用 numpy.outer() 方法。第一個引數 a 是第一個輸入向量。如果輸入不是一維的,則將其展平。第二個引數 b 是第二個輸入向量。如果輸入不是一維的,則將其展平。第三個引數 out 是儲存結果的位置。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立兩個 NumPy 一維陣列。第一個陣列是字母向量。第二個陣列是整數陣列 -

arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

顯示陣列 -

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

檢查兩個陣列的維度 -

print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

檢查兩個陣列的形狀 -

print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

要獲取陣列與字母向量的外積,請使用 numpy.outer() 方法 -

print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))

示例

import numpy as np

# Creating two numpy One-Dimensional arrays using the array() method
# The 1st array is a vector of letters
# The 2nd array is an integer array
arr1 = np.array(['p', 'q', 'r', 's'], dtype=object)
arr2 = np.array([2, 3, 1, 3])

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To get the Outer product of an array with vector of letters, use the numpy.outer() method in Python
print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))

輸出

Array1...
['p' 'q' 'r' 's']

Array2...
[2 3 1 3]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(4,)

Shape of Array2...
(4,)

Result (Outer Product)...
[['pp' 'ppp' 'p' 'ppp']
['qq' 'qqq' 'q' 'qqq']
['rr' 'rrr' 'r' 'rrr']
['ss' 'sss' 's' 'sss']]

更新於: 2022年3月2日

95 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.