NumPy 技巧和竅門

2021-09-03 17:43 更新

在這里,我們提供了一個(gè)簡短而有用的提示列表。

“自動(dòng)”整形

要更改數(shù)組的維度,可以省略隨后將自動(dòng)推導(dǎo)出的大小之一:

  1. >>> a = np.arange(30)
  2. >>> b = a.reshape((2, -1, 3)) # -1 means "whatever is needed"
  3. >>> b.shape
  4. (2, 5, 3)
  5. >>> b
  6. array([[[ 0, 1, 2],
  7. [ 3, 4, 5],
  8. [ 6, 7, 8],
  9. [ 9, 10, 11],
  10. [12, 13, 14]],
  11. [[15, 16, 17],
  12. [18, 19, 20],
  13. [21, 22, 23],
  14. [24, 25, 26],
  15. [27, 28, 29]]])

向量堆疊

我們?nèi)绾螐囊粋€(gè)大小相等的行向量列表構(gòu)造一個(gè)二維數(shù)組?在 MATLAB 中,這很容易:如果xy是兩個(gè)長度相同的向量,只需要讓m=[x;y]。在NumPy的通過功能的工作原理column_stack,dstack,hstackvstack,視維在堆疊是必須要做的。例如:

  1. >>> x = np.arange(0, 10, 2)
  2. >>> y = np.arange(5)
  3. >>> m = np.vstack([x, y])
  4. >>> m
  5. array([[0, 2, 4, 6, 8],
  6. [0, 1, 2, 3, 4]])
  7. >>> xy = np.hstack([x, y])
  8. >>> xy
  9. array([0, 2, 4, 6, 8, 0, 1, 2, 3, 4])

超過兩個(gè)維度的這些函數(shù)背后的邏輯可能很奇怪。

直方圖

histogram應(yīng)用于數(shù)組的 NumPy函數(shù)返回一對向量:數(shù)組的直方圖和 bin 邊緣的向量。注意:?matplotlib還有一個(gè)函數(shù)來構(gòu)建hist與 NumPy 中的直方圖不同的直方圖(在 Matlab 中稱為)。主要區(qū)別是pylab.hist自動(dòng)繪制直方圖,而?numpy.histogram只生成數(shù)據(jù)。

  1. import numpy as np
  2. >>> rg = np.random.default_rng(1)
  3. >>> import matplotlib.pyplot as plt
  4. >>> # Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
  5. >>> mu, sigma = 2, 0.5
  6. >>> v = rg.normal(mu, sigma, 10000)
  7. >>> # Plot a normalized histogram with 50 bins
  8. >>> plt.hist(v, bins=50, density=True) # matplotlib version (plot)
  9. >>> # Compute the histogram with numpy and then plot it
  10. >>> (n, bins) = np.histogram(v, bins=50, density=True) # NumPy version (no plot)
  11. >>> plt.plot(.5 * (bins[1:] + bins[:-1]), n)

使用 Matplotlib >=3.4,還可以使用.plt.stairs(n,?bins)

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號