How to iterate through a StatsBase.Histogram

let me start my first post by saying thank you for all the hard work from the community. I really enjoy diving into the julia programming language.

I am currently playing around with Monte Carlo simulations in julia, right now I am implementing reweighting techniques in particular. For this I need to handle histograms. After writing my first histograms as dictionaries (of course working with discrete states), I found StatsBase.Histograms to be quite neat for my cause. One feature that I do not get implemented nicely, however, is to iterate over the whole histogram.

For example, with a dictionary I can do the following

for (arg, value) in Dict

However, to get this done for StatsBase.Histograms, I am currently doing

for (i, arg) in enumerate(hist.edges[1])
  value = hist.weights[i]

How can I nicely iterate over such histograms?
Thanks a lot


for (edge, weight) in zip(hist.edges[1], hist.weights)
    @show edge, weight
1 Like

Thanks jiing,

I was not familiar with the zip() function. Does this bring performance overhead?

Also, I was wondering if there is a way to do this along all dimensions? Let’s imagine I do

h = fit(Histogram, (rand(100),rand(100)))

And let’s further imagine I do not know the dimensionality of the histogram a priori (because it is passed to the function). I was expecting something similar to iterating with CartesianIndices over a Matrix. Does something like this exist?


zip shouldn’t hinder the performance

for start, CartesianIndices(hist.weights) can give you a way to iterate over weights, and the cartesian index is your bin, if you want to convert the bin number back to edge value, you just need to access the corresponding element in hist.edges