使用histogram2d python查找平均bin值

2024-07-02 10:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,如何使用2D直方图计算容器的平均值?我有x轴和y轴的温度范围,我正试图用相应温度的箱子来绘制闪电的概率图。我正在从csv文件中读取数据,我的代码如下:

filename = 'Random_Events_All_Sorted_85GHz.csv'
df = pd.read_csv(filename)

min37 = df.min37
min85 = df.min85
verification = df.five_min_1

#Numbers
x = min85
y = min37
H = verification

#Estimate the 2D histogram
nbins = 4
H, xedges, yedges = np.histogram2d(x,y,bins=nbins)

#Rotate and flip H
H = np.rot90(H) 
H = np.flipud(H)

#Mask zeros
Hmasked = np.ma.masked_where(H==0,H)

#Plot 2D histogram using pcolor
fig1 = plt.figure()
plt.pcolormesh(xedges,yedges,Hmasked)
plt.xlabel('min 85 GHz PCT (K)')
plt.ylabel('min 37 GHz PCT (K)')
cbar = plt.colorbar()
cbar.ax.set_ylabel('Probability of Lightning (%)')

plt.show()

这是一个很漂亮的绘图,但是绘制的数据是计数,或者说每个箱子中的样本数量。验证变量是一个包含1和0的数组,其中1表示闪电,0表示没有闪电。我希望曲线图中的数据是基于验证变量的给定bin的闪电概率,因此我需要bin_mean*100才能得到这个百分比。在

我尝试使用一种类似于这里所示的方法(binning data in python with scipy/numpy),但是我很难让它适用于二维直方图。在


Tags: csvdfnp绘制plt直方图filenamemin
2条回答

至少用下面的方法是可行的

# xedges, yedges as returned by 'histogram2d'

# create an array for the output quantities
avgarr = np.zeros((nbins, nbins))

# determine the X and Y bins each sample coordinate belongs to
xbins = np.digitize(x, xedges[1:-1])
ybins = np.digitize(y, yedges[1:-1])

# calculate the bin sums (note, if you have very many samples, this is more
# effective by using 'bincount', but it requires some index arithmetics
for xb, yb, v in zip(xbins, ybins, verification):
    avgarr[yb, xb] += v

# replace 0s in H by NaNs (remove divide-by-zero complaints)
# if you do not have any further use for H after plotting, the
# copy operation is unnecessary, and this will the also take care
# of the masking (NaNs are plotted transparent)
divisor = H.copy()
divisor[divisor==0.0] = np.nan

# calculate the average
avgarr /= divisor

# now 'avgarr' contains the averages (NaNs for no-sample bins)

如果你事先知道箱子的边缘,你可以做直方图部分在相同的只是增加一行。在

有一个优雅和快速的方法来做到这一点!使用weights参数求和值:

denominator, xedges, yedges = np.histogram2d(x,y,bins=nbins)
nominator, _, _ = np.histogram2d(x,y,bins=[xedges, yedges], weights=verification)

因此,您只需在每个bin中将值的总和除以事件数:

^{pr2}$

喂!在

相关问题 更多 >