NumPy 基本操作

2021-11-06 17:33 更新

数组上的算术运算符按元素应用。创建一个新数组并填充结果。

  1. >>> a = np.array([20, 30, 40, 50])
  2. >>> b = np.arange(4)
  3. >>> b
  4. array([0, 1, 2, 3])
  5. >>> c = a - b
  6. >>> c
  7. array([20, 29, 38, 47])
  8. >>> b**2
  9. array([0, 1, 4, 9])
  10. >>> 10 * np.sin(a)
  11. array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])
  12. >>> a < 35
  13. array([ True, True, False, False])

与许多矩阵语言不同,乘积运算符*在 NumPy 数组中按元素进行运算。可以使用@运算符(在python>=3.5中)或dot函数或方法来执行矩阵乘积:

  1. >>> A = np.array([[1, 1],
  2. ... [0, 1]])
  3. >>> B = np.array([[2, 0],
  4. ... [3, 4]])
  5. >>> A * B # elementwise product
  6. array([[2, 0],
  7. [0, 4]])
  8. >>> A @ B # matrix product
  9. array([[5, 4],
  10. [3, 4]])
  11. >>> A.dot(B) # another matrix product
  12. array([[5, 4],
  13. [3, 4]])

某些操作,例如+=and *=,会修改现有数组而不是创建新数组。

  1. >>> rg = np.random.default_rng(1) # create instance of default random number generator
  2. >>> a = np.ones((2, 3), dtype=int)
  3. >>> b = rg.random((2, 3))
  4. >>> a *= 3
  5. >>> a
  6. array([[3, 3, 3],
  7. [3, 3, 3]])
  8. >>> b += a
  9. >>> b
  10. array([[3.51182162, 3.9504637 , 3.14415961],
  11. [3.94864945, 3.31183145, 3.42332645]])
  12. >>> a += b # b is not automatically converted to integer type
  13. Traceback (most recent call last):
  14. ...
  15. numpy.core._exceptions._UFuncOutputCastingError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

当处理不同类型的数组时,结果数组的类型对应于更一般或更精确的类型(一种称为向上转换的行为)。

  1. >>> a = np.ones(3, dtype=np.int32)
  2. >>> b = np.linspace(0, pi, 3)
  3. >>> b.dtype.name
  4. 'float64'
  5. >>> c = a + b
  6. >>> c
  7. array([1. , 2.57079633, 4.14159265])
  8. >>> c.dtype.name
  9. 'float64'
  10. >>> d = np.exp(c * 1j)
  11. >>> d
  12. array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,
  13. -0.54030231-0.84147098j])
  14. >>> d.dtype.name
  15. 'complex128'

许多一元运算,例如计算数组中所有元素的总和,都是作为ndarray类的方法实现的。

  1. >>> a = rg.random((2, 3))
  2. >>> a
  3. array([[0.82770259, 0.40919914, 0.54959369],
  4. [0.02755911, 0.75351311, 0.53814331]])
  5. >>> a.sum()
  6. 3.1057109529998157
  7. >>> a.min()
  8. 0.027559113243068367
  9. >>> a.max()
  10. 0.8277025938204418

默认情况下,这些操作适用于数组,就好像它是一个数字列表,无论其形状如何。但是,通过指定axis 参数,可以沿数组的指定轴应用操作:

  1. >>> b = np.arange(12).reshape(3, 4)
  2. >>> b
  3. array([[ 0, 1, 2, 3],
  4. [ 4, 5, 6, 7],
  5. [ 8, 9, 10, 11]])
  6. >>>
  7. >>> b.sum(axis=0) # sum of each column
  8. array([12, 15, 18, 21])
  9. >>>
  10. >>> b.min(axis=1) # min of each row
  11. array([0, 4, 8])
  12. >>>
  13. >>> b.cumsum(axis=1) # cumulative sum along each row
  14. array([[ 0, 1, 3, 6],
  15. [ 4, 9, 15, 22],
  16. [ 8, 17, 27, 38]])
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号