阅读(2332) (10)

NumPy 技巧和窍门

2021-09-01 09:19:49 更新

在这里,我们提供了一个简短而有用的提示列表。

“自动”整形

要更改数组的维度,可以省略随后将自动推导出的大小之一:

>>> 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]]])

向量堆叠

我们如何从一个大小相等的行向量列表构造一个二维数组?在 MATLAB 中,这很容易:如果xy是两个长度相同的向量,只需要让m=[x;y]。在NumPy的通过功能的工作原理column_stackdstackhstackvstack,视维在堆叠是必须要做的。例如:

>>> 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])

超过两个维度的这些函数背后的逻辑可能很奇怪。

直方图

histogram应用于数组的 NumPy函数返回一对向量:数组的直方图和 bin 边缘的向量。注意: matplotlib还有一个函数来构建hist与 NumPy 中的直方图不同的直方图(在 Matlab 中称为)。主要区别是pylab.hist自动绘制直方图,而 numpy.histogram只生成数据。

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)