首页 > 解决方案 > 来自两个耦合阵列的直方图

问题描述

我有两个数组:一个用于粒子位置X,一个用于相应的速度V。我想为粒子位置创建一个直方图,其中每个 bin 宽度为 1,并且对于每个 bin,我想计算该特定 bin 中粒子的相关速度的方差。

做位置直方图很简单:

import numpy as np
import matplotlib.pyplot as plt

X = np.random.randn(1000)
V = 3*np.random.randn(1000) + 40

bins = np.arange(int(X.min()) - 0.5, int(X.max())+1.5, 1)

plt.hist(X, bins=bins, facecolor = '#2ab0ff', edgecolor='#169acf', linewidth=0.7)

但是,我想根据V向量计算每个 bin 中粒子的速度方差(如果 bin 中有 3 个以 -3 为中心的粒子,我想计算 3 个速度值的方差)。我不确定如何有效地做到这一点,因为没有跟踪从X向量到直方图的映射。

关于如何解决这个问题的任何想法?

谢谢!

标签: pythonnumpyhistogram

解决方案


您可能想要使用函数scipy.stats.binned_statistics

这是一个例子。

import numpy as np
from scipy.stats import binned_statistic
import matplotlib.pyplot as plt

X = np.random.randn(1000)
V = 3*np.random.randn(1000) + 40

hist, bins, stst = binned_statistic(X, V, statistic='std')

bin_centres = (bins[1:] + bins[:-1]) / 2

plt.plot(bin_centres, hist)
plt.show()

推荐阅读