在NumPy中按元素划分参数并以不同类型显示结果


要按元素划分参数,请在Python NumPy中使用**numpy.divide()**方法。arr1被视为被除数数组。arr2被视为除数数组。使用“**dtype**”参数将输出设置为“**float**”。

out是将结果存储到的位置。如果提供,则其形状必须与输入广播到的形状相同。如果不提供或为None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持广泛的硬件和计算平台,并且与分布式、GPU和稀疏数组库配合良好。

步骤

首先,导入所需的库:

import numpy as np

创建两个二维数组:

arr1 = np.array([[14, 28, 56], [84, 56, 112]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

显示数组:

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)

要按元素划分参数,请在Python NumPy中使用numpy.divide()方法。arr1被视为被除数数组。arr2被视为除数数组。使用“dtype”参数将输出设置为“float”。

print("
Result (divide element-wise)...
",np.divide(arr1, arr2, dtype = 'float'))

示例

import numpy as np

# Create two 2D arrays
arr1 = np.array([[14, 28, 56], [84, 56, 112]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

# 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) # To divide arguments element-wise, use the numpy.divide() method in Python Numpy # The arr1 is considered Dividend array # The arr2 is considered Divisor array # The output is set "float" using the "dtype" parameter print("
Result (divide element-wise)...
",np.divide(arr1, arr2, dtype = 'float'))

输出

Array 1...
[[ 14 28 56]
[ 84 56 112]]

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

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 3)

Our Array 2 Shape...
(2, 3)

Result (divide element-wise)...
[[2. 2. 2.66666667]
[3. 1.6 2. ]]

更新于:2022年2月7日

317 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告