Skip to content

NumPy - 算术运算

NumPy 在数组(array)上执行快速、元素级别的(element-wise)算术运算方面表现出色。这些操作被实现为 通用函数(ufuncs),它们能高效地对 ndarray 对象进行操作。

对于两个数组之间的算术运算(例如,a + b,a * b),NumPy 要求数组要么形状完全相同,要么根据 广播(broadcasting)规则兼容。广播(broadcasting)允许 NumPy 隐式地扩展较小的数组,使其形状与较大的数组匹配,从而即使在形状不完全一致时也能进行元素级别的运算。 (了解更多关于广播的内容)

标准的 Python 算术运算符(+, -, *, /, **, //, %)已被 NumPy 重载,用于对数组执行元素级别的运算。这通常是表达计算最直观的方式。

示例:使用广播进行元素级别运算

Section titled “示例:使用广播进行元素级别运算”
import numpy as np
# Create a 3x3 array
a = np.arange(9, dtype=np.float64).reshape(3, 3)
print(f"First array (a):\n{a}\n")
# Create a 1D array (compatible for broadcasting with 'a')
b = np.array([10., 100., 1000.])
print(f"Second array (b): {b}\n")
# Element-wise addition (b is broadcast across rows of a)
print(f"Add a + b:\n{a + b}\n")
# Element-wise subtraction
print(f"Subtract a - b:\n{a - b}\n")
# Element-wise multiplication
print(f"Multiply a * b:\n{a * b}\n")
# Element-wise division
print(f"Divide a / b:\n{a / b}\n")

输出:

First array (a):
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Second array (b): [ 10. 100. 1000.]
Add a + b:
[[ 10. 101. 1002.]
[ 13. 104. 1005.]
[ 16. 107. 1008.]]
Subtract a - b:
[[ -10. -99. -998.]
[ -7. -96. -995.]
[ -4. -93. -992.]]
Multiply a * b:
[[ 0. 100. 2000.]
[ 30. 400. 5000.]
[ 60. 700. 8000.]]
Divide a / b:
[[0. 0.01 0.002]
[0.3 0.04 0.005]
[0.6 0.07 0.008]]

NumPy 也为这些操作提供了显式的 ufuncs(例如,np.add、np.subtract、np.multiply、np.divide),有时可以通过特定参数提供更多控制或选项。

计算元素的倒数(1/x)。注意除以零的情况,这会导致 inf(无穷大)并引发 RuntimeWarning(运行时警告)。

import numpy as np
a = np.array([0.25, 1.33, 1., 0., -2.], dtype=np.float64)
print(f"Original array: {a}\n")
# Calculate reciprocal
reciprocal_a = np.reciprocal(a)
print(f"Reciprocal: {reciprocal_a}")
# Example with an integer (results in 0 for integers > 1)
int_arr = np.array([100], dtype=int)
print(f"\nInteger array: {int_arr}")
print(f"Reciprocal of integer: {np.reciprocal(int_arr)}") # Output: [0]

输出(为简洁起见省略警告):

Original array: [ 0.25 1.33 1. 0. -2. ]
Reciprocal: [ 4. 0.7518797 1. inf -0.5 ]
Integer array: [100]
Reciprocal of integer: [0]

将第一个数组的元素提高到第二个数组(或标量)对应元素的幂次方。

import numpy as np
a = np.array([1, 2, 3])
print(f"Base array (a): {a}")
# Square each element
print(f"a squared (a ** 2): {np.power(a, 2)}")
# Raise elements to different powers
b = np.array([1, 2, 3])
print(f"Exponent array (b): {b}")
print(f"a raised to power b: {np.power(a, b)}")

输出:

Base array (a): [1 2 3]
a squared (a ** 2): [1 4 9]
Exponent array (b): [1 2 3]
a raised to power b: [ 1 4 27]

计算除法的元素级余数。对于正值,np.mod() 和 np.remainder() 是等效的;对于负值,它们可能因约定而略有不同。

import numpy as np
a = np.array([10, 20, 30])
b = np.array([3, 5, 7])
print(f"First array (a): {a}")
print(f"Second array (b): {b}\n")
print(f"Remainder using np.mod(a, b): {np.mod(a, b)}")
print(f"Remainder using np.remainder(a, b): {np.remainder(a, b)}")

输出:

First array (a): [10 20 30]
Second array (b): [3 5 7]
Remainder using np.mod(a, b): [1 0 2]
Remainder using np.remainder(a, b): [1 0 2]

NumPy 无缝支持复数数据类型(np.complex64、np.complex128)的数组。有一些特定函数可用于提取复数的部分:

  • numpy.real(): 返回实部。
  • numpy.imag(): 返回虚部。
  • numpy.conj() 或 numpy.conjugate(): 返回复共轭(改变虚部的符号)。
  • numpy.angle(): 返回角度(默认为弧度,如果 deg=True 则为度)。
import numpy as np
# Note: Use 'j' for the imaginary unit in Python
c = np.array([-5.6j, 0.2j, 11., 1 + 1j])
print(f"Complex array: {c}\n")
print(f"Real part: {np.real(c)}")
print(f"Imaginary part: {np.imag(c)}")
print(f"Conjugate: {np.conj(c)}")
print(f"Angle (radians): {np.angle(c)}")
print(f"Angle (degrees): {np.angle(c, deg=True)}")

输出:

Complex array: [ 0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ]
Real part: [ 0. 0. 11. 1.]
Imaginary part: [-5.6 0.2 0. 1. ]
Conjugate: [ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ]
Angle (radians): [-1.57079633 1.57079633 0. 0.78539816]
Angle (degrees): [-90. 90. 0. 45.]

有关通用函数的完整列表,请参阅 NumPy ufunc 文档。