NumPy 技巧和竅門

2021-09-03 17:43 更新

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

“自動(dòng)”整形

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

>>> a = np.arange(30)
>>> b = a.reshape((2, -1, 3))  # -1 means "whatever is needed"
>>> b.shape
(2, 5, 3)
>>> b
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11],
        [12, 13, 14]],


       [[15, 16, 17],
        [18, 19, 20],
        [21, 22, 23],
        [24, 25, 26],
        [27, 28, 29]]])

向量堆疊

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

>>> x = np.arange(0, 10, 2)
>>> y = np.arange(5)
>>> m = np.vstack([x, y])
>>> m
array([[0, 2, 4, 6, 8],
       [0, 1, 2, 3, 4]])
>>> xy = np.hstack([x, y])
>>> xy
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ù)。

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

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

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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號