User Tools

Site Tools


other:python:misc_by_jyp

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
other:python:misc_by_jyp [2022/02/21 17:31] – [numpy related stuff] Added ufuncs jypeterother:python:misc_by_jyp [2022/02/21 17:46] – [numpy related stuff] Added reduceat jypeter
Line 275: Line 275:
 >>> sorted_vals[0:3].sum(), sorted_vals[3:6].sum(), sorted_vals[6:10].sum() >>> sorted_vals[0:3].sum(), sorted_vals[3:6].sum(), sorted_vals[6:10].sum()
 (3.0, 4.5, 8.0)</code> (3.0, 4.5, 8.0)</code>
 +
 +=== Applying a ufunc over specified sections of an array ===
 +
 +The [[https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduceat.html#numpy.ufunc.reduceat|reduceat]] function can be used to avoid explicit python loops, and improve the speed (but not the readability...) of a script. The example below //improves// what has been shown above
 +
 +<code># Define a list with the boundaries of the intervals we want to apply the 'add' function to
 +# We need to add the beginning index (0), AND remove the last index
 +# (reduceat will automatically go to the end of the input array
 +>>> nb_unique
 +array([3, 3, 4])
 +>>> slices_indices = [0] + list(np.add.accumulate(nb_unique))
 +>>> slices_indices.pop() # Remove last element
 +10
 +>>> slices_indices
 +[0, 3, 6]
 +
 +# Compute the sums over the selected intervals with just one call
 +>>> np.add.reduceat(np.sort(vals), slices_indices)
 +array([3. , 4.5, 8. ])</code>
  
 /* /*
other/python/misc_by_jyp.txt · Last modified: 2024/11/04 15:01 by jypeter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki