Last active
April 5, 2020 16:32
-
-
Save masdeseiscaracteres/c8ea34b439168ecdab70eef906b966de to your computer and use it in GitHub Desktop.
Numpy groupby (inspired in the implementation in https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def groupby(keys, values, func=np.sum, axis=0, stable=True): | |
if axis != 0: | |
raise NotImplementedError | |
stable = True | |
sorter = np.argsort(keys, kind='mergesort' if stable else 'quicksort') | |
# computed sorted keys | |
keys_sorted = keys[sorter] | |
# the slicing points of the bins to reduce over | |
flag = keys_sorted[:-1] != keys_sorted[1:] # True is final element of a group | |
length = len(keys) | |
slices = np.concatenate(([0], np.flatnonzero(flag) + 1, [length])) | |
values = np.take(values, sorter, axis=axis) | |
if isinstance(func, ufunc): | |
agg_values = func.__getattribute__('reduceat')(values, slices[:-1]) | |
else: | |
sub_arr_list = np.array_split(values, slices[1:-1]) | |
agg_values = np.array([func(sub_arr) for sub_arr in sub_arr_list]) | |
unique_keys = keys_sorted[slices[:-1]] | |
return np.concatenate((unique_keys[:,None], agg_values[:,None]), axis=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples
Small array
Large array