在 Python 中获取带有字母向量的数组的外积

pythonnumpyserver side programmingprogramming更新于 2024/5/14 8:12:17

给定两个向量,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("\n结果 (外积)...\n",np.outer(arr1, arr2))

示例

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)

# 要获取带有字母向量的数组的外积,请使用 Python 中的 numpy.outer() 方法
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']]

相关文章


有用资源