NumPy 基本操作

2021-11-06 17:33 更新

數(shù)組上的算術運算符按元素應用。創(chuàng)建一個新數(shù)組并填充結果。

  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 數(shù)組中按元素進行運算??梢允褂?code>@運算符(在python>=3.5中)或dot函數(shù)或方法來執(zhí)行矩陣乘積:

  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?*=,會修改現(xiàn)有數(shù)組而不是創(chuàng)建新數(shù)組。

  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'

當處理不同類型的數(shù)組時,結果數(shù)組的類型對應于更一般或更精確的類型(一種稱為向上轉換的行為)。

  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'

許多一元運算,例如計算數(shù)組中所有元素的總和,都是作為ndarray類的方法實現(xiàn)的。

  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

默認情況下,這些操作適用于數(shù)組,就好像它是一個數(shù)字列表,無論其形狀如何。但是,通過指定axis?參數(shù),可以沿數(shù)組的指定軸應用操作:

  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

公眾號
微信公眾號

編程獅公眾號