【问题标题】:Extracting data from a histogram with custom bins in Python在 Python 中使用自定义 bin 从直方图中提取数据
【发布时间】:2021-08-28 17:00:15
【问题描述】:

我有一个包含两个粒子之间距离的数据集,我想将这些数据分箱到自定义箱中。例如,我想查看从 1 到 2 微米的间隔中有多少距离值,依此类推。我写了一个关于它的代码,它似乎工作。这是我这部分的代码:

#Custom binning of data

bins= [0,1,2,3,4,5,6,7,8,9,10]
fig, ax = plt.subplots(n,m,figsize = (30,10)) #using this because I actually have 5 histograms, but only posted one here
ax.hist(dist_from_spacer1, bins=bins, edgecolor="k")
ax.set_xlabel('Distance from spacer 1 [µm]')
ax.set_ylabel('counts')
plt.xticks(bins)
plt.show()

但是,现在我希望从区间中提取这些数据值,并将它们存储到列表中。我尝试使用:

np.histogram(dist_from_spacer1, bins=bins)

但是,这只是给出了每个 bin 上有多少数据点和 bin 间隔,就像这样:

(array([  0,   0,  44, 567, 481, 279, 309, 202, 117,   0]),
 array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]))

如何获得属于每个直方图 bin 的确切数据?

【问题讨论】:

  • 好吧,如果你想要每个 bin 的 dist_from_spacer1 中的值,那么你已经将它们放在一个紧凑的表示中......在你的例子中,值 3 是 44,所以 bin 包含大小为 44 的值列表 [3, 3, 3, 3, ..., 3]。我错过了什么吗?你想要索引吗?

标签: python numpy dataset histogram binning


【解决方案1】:

是的,np.histogram 计算直方图所需的内容,因此不需要特定的数据点,只需要 bin 的边界和每个 bin 的计数。但是,通过使用 np.digitizr,垃圾箱的边界足以实现您想要的目标

counts, bins = np.histogram(dist_from_spacer1)
indices = np.digitize(dist_from_spacer1, bins)
lists = [[] for _ in range(len(bins))]
[lists[i].append(x) for i, x in zip(indices, dist_from_spacer1)

在您的情况下,垃圾箱的边界是预定义的,因此您可以直接使用np.digitize

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 2013-10-08
    • 2013-12-06
    • 2020-04-02
    相关资源
    最近更新 更多