在 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)
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP