add()
函数执行两个数组的逐元素相加。
示例
import numpy as np
# create two arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# perform element-wise addition of the two arrays
result = np.add(array1, array2)
print(result)
# Output: [5 7 9]
add() 语法
add()
的语法是
numpy.add(x1, x2, out = None, where = True, dtype = None)
add() 参数
add()
函数接受以下参数
x1
和x2
- 要相加的两个输入数组或标量out
(可选) - 用于存储结果的输出数组where
(可选) - 一个布尔数组或条件,用于指定要相加的元素dtype
(可选) - 输出数组的数据类型
add() 返回值
add()
函数返回一个数组,其中包含两个数组 — x1 和 x2 — 中对应元素(或元素)的和。
示例 1:用标量(单个值)添加 NumPy 数组
import numpy as np
# create an array
array1 = np.array([1, 2, 3])
# add a scalar value to the array
result = np.add(array1, 10)
print(result)
输出
[11 12 13]
此处,np.add()
函数用于将标量值 10 添加到 array1 数组的每个元素。
示例 2:add() 中 out 和 where 的用法
import numpy as np
# create two input arrays
array1 = np.array([1, 2, 3, 5])
array2 = np.array([10, 20, 30, 50])
# create a boolean array to specify the condition for element selection
condition = np.array([True, False, True, True])
# create an empty array to store the subtracted values
result = np.empty_like(array1)
# add elements in array1 and array2 based on values in the condition array and
# store the sum in the result array
np.add(array1, array2, where=condition, out=result)
print(result)
输出
[11 0 33 55]
输出显示了加法运算的结果,其中 array1 和 array2 中的元素仅在 condition 数组中的相应条件为 True
时相加。
result
中的第二个元素为 0,因为相应的条件值为 False,因此该元素不执行加法。
此处,out=result
指定 np.add()
的输出应存储在 result 数组中
示例 3:add() 中 dtype 参数的用法
import numpy as np
# create two arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# perform addition with floating-point data type
resultFloat = np.add(array1, array2, dtype=np.float64)
# perform addition with integer data type
resultInt = np.add(array1, array2, dtype=np.int32)
# print the result with floating-point data type
print("Floating-point result:")
print(resultFloat)
# print the result with integer data type
print("Integer result:")
print(resultInt)
输出
Floating-point result: [5. 7. 9.] Integer result: [5 7 9]
这里,通过指定所需的 dtype
,我们可以根据需要控制输出数组的数据类型。
此处,我们使用 dtype
参数指定了输出数组的数据类型。
注意:要了解有关 dtype
参数的更多信息,请访问 NumPy 数据类型。