Bucket Numbers into Histogram Bin Counts in Python
Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.
Python code
32 linesfrom collections import Counter
def histogram_bins(numbers, num_bins):
"""Bucket numbers into histogram bin counts."""
if not numbers:
return []
min_val = min(numbers)
max_val = max(numbers)
bin_width = (max_val - min_val) / num_bins
# Handle edge case where all values are identical
if bin_width == 0:
return [len(numbers)] + [0] * (num_bins - 1)
counts = [0] * num_bins
for number in numbers:
# Compute bin index, with max value going into the last bin
index = min(int((number - min_val) / bin_width), num_bins - 1)
counts[index] += 1
return counts
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
bins = 5
result = histogram_bins(data, bins)
print(f"Data: {data}")
print(f"Bins: {bins}")
print(f"Counts: {result}")
print(f"Sum of counts: {sum(result)} (should equal {len(data)})")
Output
Data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Bins: 5
Counts: [2, 2, 2, 2, 2]
Sum of counts: 10 (should equal 10)
How it works
The function first computes the minimum and maximum of the data to establish the range, then divides that range by the number of bins to get a uniform bin width. For each number, it calculates an index by normalizing the number to its distance from the minimum and dividing by the bin width, then clamping to the last bin to handle the maximum value safely. A special case returns all counts in the first bin when all numbers are identical (bin width zero). The algorithm runs in O(n) time, making it efficient for large datasets.
Common mistakes
- Forgetting to clamp the computed index to `num_bins - 1` so the maximum value lands in the last bin.
- Not handling the case where all values are equal, which would cause division by zero.
- Assuming the input is sorted when the algorithm works on unsorted data.
Variations
- Use `numpy.histogram` or `numpy.digitize` for faster bins on large arrays.
- Return bin edges alongside counts to build a full histogram representation.
Real-world use cases
- Analyzing server response time distributions to create latency histograms for monitoring dashboards.
- Grouping customer purchase amounts into price bands for marketing segmentation analysis.
- Building image pixel intensity histograms for contrast adjustment in computer vision preprocessing.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
- Drop Elements From Start While Condition Is True in Python easy
Keep learning
Related tutorials and quizzes for this topic.