Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import numpy as np 

2 

3 

4def int_binned_stat(ids, values, statistic=np.mean): 

5 """ 

6 Like scipy.binned_statistic, but for unique integer ids. 

7 

8 Parameters 

9 ---------- 

10 ids : array-like of ints 

11 The integer ID for each value 

12 values : array-like 

13 The values to be combined 

14 statistic : function (np.mean) 

15 Function to run on the values that have matching ids. 

16 

17 Returns 

18 ------- 

19 unique ids, binned values 

20 """ 

21 

22 uids = np.unique(ids) 

23 order = np.argsort(ids) 

24 

25 ordered_ids = ids[order] 

26 ordered_values = values[order] 

27 

28 left = np.searchsorted(ordered_ids, uids, side='left') 

29 right = np.searchsorted(ordered_ids, uids, side='right') 

30 

31 stat_results = [] 

32 for le, ri in zip(left, right): 

33 stat_results.append(statistic(ordered_values[le:ri])) 

34 

35 return uids, np.array(stat_results)