NumPy grouping using itertools.groupby performance
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Grouping data in NumPy arrays often leads developers to itertools.groupby, but this approach is slow because it requires sorting the array, converting to Python objects, and iterating element-by-element. NumPy-native alternatives — np.unique with return_counts/return_inverse, boolean indexing, and np.bincount — are 10-100x faster because they operate entirely in C without Python loop overhead. For DataFrame-like groupby operations, pandas is usually the best choice.
itertools.groupby with NumPy (Slow)
This works but is slow: argsort is fast (O(n log n)), but groupby iterates in Python, creating Python objects for each element. For large arrays, this bottleneck dominates.
Fast Alternative: np.unique with return_inverse
np.unique with return_inverse maps each element to its group index. np.bincount with weights computes weighted sums per group — all in C, no Python loop.
Counting Elements per Group
np.bincount is the fastest option for non-negative integer keys. np.unique with return_counts works with any data type.
Group Mean, Min, Max
np.maximum.reduceat applies the maximum ufunc to segments of the sorted array. Combined with searchsorted to find group boundaries, this avoids Python loops entirely.
Boolean Indexing for Simple Groups
For a small number of groups (under 10-20), boolean indexing is simple and fast. Each pass creates a mask and selects matching elements — all vectorized.
pandas GroupBy (Best for Complex Operations)
For complex groupby operations (multiple aggregations, string keys, custom functions), pandas is the practical choice. The overhead of creating a DataFrame is negligible compared to the flexibility gained.
Performance Comparison
Typical results for 1M elements, 100 groups:
| Method | Time | Relative Speed |
| itertools.groupby | 2.5s | 1x |
| pandas groupby | 0.15s | 17x |
| np.bincount | 0.02s | 125x |
Common Pitfalls
- Forgetting to sort before itertools.groupby:
itertools.groupbygroups consecutive equal elements. Without sorting first, it creates multiple groups for the same key. Alwaysargsortand reindex before using it. - Using itertools.groupby for large arrays: The Python-level iteration overhead makes it 50-100x slower than NumPy-native approaches. Use
np.bincount,np.unique, or pandas for arrays over a few thousand elements. - np.bincount only works with non-negative integers: If your keys are floats, strings, or negative numbers,
np.bincountdoes not work. Usenp.unique(return_inverse=True)to map arbitrary keys to integer indices first. - Memory usage with np.unique on large arrays:
np.uniquesorts a copy of the array internally, doubling memory usage. For very large arrays, consider processing in chunks or using pandas which handles memory more efficiently. - Ignoring pandas for complex grouping: Pure NumPy groupby is fast for simple sum/mean/count but becomes complex for multi-column grouping, custom aggregations, or string keys. pandas handles these cases with simpler code and acceptable performance.
Summary
- Avoid
itertools.groupbyfor NumPy arrays — it requires sorting and Python-level iteration - Use
np.bincount(keys, weights=values)for the fastest group sums with integer keys - Use
np.unique(return_inverse=True)to map arbitrary keys to integer indices - Use
np.maximum.reduceaton sorted data for group min/max operations - Use pandas
groupby()for complex aggregations, string keys, or multi-column grouping np.bincountis 50-125x faster thanitertools.groupbyfor large arrays
Related reading
- numpy How can I select specific indexes in an np array for k-fold cross validation?
- Numpy is installed but still getting error
- Numpy linear regression with regularization
- numpy matrix vector multiplication
- Object comparison in JavaScript
- Objective-C ARC strong vs retain and weak vs assign
- numpy max vs amax vs maximum
- numpy random choice in Tensorflow

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.