NumPy subtract()

subtract() 函数执行两个数组的逐元素减法。

示例

import numpy as np

# create two arrays
array1 = np.array([4, 5, 6])  
array2 = np.array([2, 1, 3])  

# perform element-wise subtraction of the two arrays result = np.subtract(array1, array2)
print(result) # Output: [2 4 3]

subtract() 语法

subtract() 的语法是

numpy.subtract(x1, x2, out = None, where = True, dtype = None)

subtract() 参数

subtract() 函数接受以下参数

  • x1x2 - 要相减的两个输入数组或标量
  • out (可选) - 用于存储结果的输出数组
  • where (可选) - 一个布尔数组或条件,用于指定要减去哪些元素
  • dtype (可选) - 输出数组的数据类型

subtract() 返回值

np.subtract() 函数返回一个数组,其中包含两个数组之间或数组与标量值之间的逐元素减法的结果。


示例 1:从 NumPy 数组中减去一个标量值

import numpy as np

# create an array
arr = np.array([10, 20, 30])

# subtract a scalar value from the array result = np.subtract(arr, 5)
print(result)

输出

[ 5 15 25]

这里,np.subtract() 函数用于从 arr 数组的每个元素中减去标量值 5


示例 2:subtract() 中 out 和 where 的用法

import numpy as np

# create two input arrays
array1 = np.array([10, 20, 30, 50])
array2 = np.array([1, 2, 3, 5])

# create a Boolean array as a condition for subtraction
condition = np.array([True, False, True, True])

# create an empty array to store the subtracted values
result = np.empty_like(array1)

# perform element-wise subtraction between array1 and array2, # only where the condition is True and store output in result array np.subtract(array1, array2, where=condition, out=result)
print(result)

输出

[ 9  0 27 45]

输出显示了减法操作的结果,其中 array1array2 中的元素仅在相应条件为 True 时才相减。

result 中的第二个元素为 0,因为相应的条件值为 False,因此该元素的减法未发生。

这里,out=result 指定 np.subtract() 的输出将存储在 result 数组中


示例 3:subtract() 中 dtype 参数的用法

import numpy as np

# create two arrays
array1 = np.array([14, 25, 46])
array2 = np.array([7, 12, 23])

# subtract array2 from array1 with a floating-point data type resultFloat = np.subtract(array1, array2, dtype=np.float64)
# subtract array2 from array1 with a integer data type resultInt = np.subtract(array1, array2, dtype=np.int32)
print("Floating-point result:") print(resultFloat) print("\nInteger result:") print(resultInt)

输出

Floating-point result:
[ 7. 13. 23.]

Integer result:
[ 7 13 23]

这里,通过指定所需的 dtype,我们可以根据需要控制输出数组的数据类型。

注意:要了解有关 dtype 参数的更多信息,请访问 NumPy 数据类型

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战