Here it is given a possible method in order to count data with weights. That solution works. However, it is ~140 times slower than the Bincounts
function. See, e.g. the following code:
Ndata = 10^6;
SeedRandom[321];
data = RandomReal[{0, 10}, Ndata];
weights = RandomReal[{.9, 1.1}, Ndata];
bins = Table[i, {i, 0, 10}];
AbsoluteTiming[Last[HistogramList[WeightedData[data, weights], {bins}]]]
AbsoluteTiming[BinCounts[data, {bins}]]
I would like to know if it is possible to make a faster function.
A faster method could be to apply the function proposed here to the output of BinLists
:
myFn = Merge[KeyIntersection[PositionIndex /@ {##}], Identity] &;
blist = BinLists[data, {bins}]
myFn[blist, Partition[data, 1]]
(*<|{0.986147} -> {{1}, {3}}, {1.49106} -> {{2}, {6}}, {3.23491} -> {{4}, {7}}, {7.15785} -> {{8}, {5}}, {8.9058} -> {{9}, {9}}|>*)
Then I could use the latter output (the positions) to sum the weights. However, myFn
does not identify the positions if there are more elements inside a bin.
Does someone know how to improve upon this attempt? Other solutions are most welcome. Perhaps one could see how does the Python function numpy.bincount
work?