在NumPy中逐元素相加参数并在不同类型中显示结果
要逐元素相加参数,请在Python NumPy中使用**numpy.add()**方法。使用“**dtype**”参数将输出设置为“**float**”。
out是存储结果的位置。如果提供,则其形状必须与输入广播到的形状相同。如果未提供或为None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。
条件在输入上进行广播。在条件为True的位置,out数组将设置为ufunc结果。在其他地方,out数组将保留其原始值。请注意,如果通过默认的out=None创建未初始化的out数组,则其中条件为False的位置将保持未初始化状态。
步骤
首先,导入所需的库:
import numpy as np
创建两个包含int元素的二维数组:
arr1 = np.array([[5, 10, 15], [25, 30, 35]]) 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.add()方法。使用“dtype”参数将输出设置为“float”:
print("
Result (adding element-wise)...
",np.add(arr1, arr2, dtype = 'float'))示例
import numpy as np
# Create two 2D arrays with int elements
arr1 = np.array([[5, 10, 15], [25, 30, 35]])
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 add arguments element-wise, use the numpy.add() method in Python Numpy
# The output is set "float" using the "dtype" parameter
print("
Result (adding element-wise)...
",np.add(arr1, arr2, dtype = 'float'))输出
Array 1... [[ 5 10 15] [25 30 35]] 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 (adding element-wise)... [[12. 24. 36.] [53. 65. 91.]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP