对列表进行排序的另一种方法是使用 NumPy 数组并使用 np.sort() 进行排序。使用数组的优势在于在计算 y=f(x) 之类的函数时进行矢量化操作。以下是绘制正态分布的示例:
不使用排序数据
mu, sigma = 0, 0.1
x = np.random.normal(mu, sigma, 200)
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(x,f, '-bo', ms = 2)
输出 1
使用 np.sort() 这允许在计算正态分布时直接使用排序数组 x。
mu, sigma = 0, 0.1
x = np.sort(np.random.normal(mu, sigma, 200))
# or use x = np.random.normal(mu, sigma, 200).sort()
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(x,f, '-bo', ms = 2)
或者,如果您已经有未排序的 x 和 y 数据,您可以使用 numpy.argsort 对它们进行后验排序
mu, sigma = 0, 0.1
x = np.random.normal(mu, sigma, 200)
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(np.sort(x), f[np.argsort(x)], '-bo', ms = 2)
请注意,上面的代码使用了两次sort():首先使用np.sort(x),然后使用f[np.argsort(x)]。 sort() 调用总数可以减少到一个:
# once you have your x and f...
indices = np.argsort(x)
plt.plot(x[indices], f[indices], '-bo', ms = 2)
在这两种情况下,输出都是
输出 2