other:python:misc_by_jyp
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
other:python:misc_by_jyp [2021/10/27 16:05] – Added sets jypeter | other:python:misc_by_jyp [2022/02/21 17:46] – [numpy related stuff] Added reduceat jypeter | ||
---|---|---|---|
Line 206: | Line 206: | ||
==== Sorting ==== | ==== Sorting ==== | ||
+ | * When dealing with **numerical values**, you should use the [[https:// | ||
* [[https:// | * [[https:// | ||
* Example: sorting the keys and the values of a dictionary, and then using the '' | * Example: sorting the keys and the values of a dictionary, and then using the '' | ||
Line 220: | Line 221: | ||
[' | [' | ||
+ | ==== numpy related stuff ==== | ||
+ | |||
+ | === Finding and counting unique values === | ||
+ | |||
+ | Use '' | ||
+ | |||
+ | < | ||
+ | >>> | ||
+ | array([1. , 2. , 1. , 2. , 2. , 1.5, 1. , 1.5, 2. , 1.5]) | ||
+ | |||
+ | >>> | ||
+ | array([1. , 1.5, 2. ]) | ||
+ | >>> | ||
+ | >>> | ||
+ | array([1. , 1.5, 2. ]) | ||
+ | >>> | ||
+ | array([3, 3, 4]) | ||
+ | |||
+ | >>> | ||
+ | >>> | ||
+ | array([1. , 1. , 1. , 1.5, 1.5, 1.5, 2. , 2. , 2. , 2. ])</ | ||
+ | |||
+ | === Applying a ufunc over all the elements of an array === | ||
+ | |||
+ | There are all sorts of //ufuncs// (Universal Functions), and we will just use below '' | ||
+ | |||
+ | < | ||
+ | >>> | ||
+ | 15.5 | ||
+ | >>> | ||
+ | 15.5 | ||
+ | >>> | ||
+ | 15.5 | ||
+ | |||
+ | # Compute the sum of the elements of ' | ||
+ | # AND keep (accumulate) the intermediate results | ||
+ | >>> | ||
+ | array([3, 3, 4]) | ||
+ | >>> | ||
+ | array([ 3, 6, 10]) | ||
+ | |||
+ | # The accumulated values can be used as indices to separate the different groups of sorted values! | ||
+ | >>> | ||
+ | array([1. , 1. , 1. , 1.5, 1.5, 1.5, 2. , 2. , 2. , 2. ]) | ||
+ | >>> | ||
+ | array([1., 1., 1.]) | ||
+ | >>> | ||
+ | array([1.5, 1.5, 1.5]) | ||
+ | >>> | ||
+ | array([2., 2., 2., 2.]) | ||
+ | |||
+ | # Compute the sum of each equal-value group | ||
+ | >>> | ||
+ | (3.0, 4.5, 8.0)</ | ||
+ | |||
+ | === Applying a ufunc over specified sections of an array === | ||
+ | |||
+ | The [[https:// | ||
+ | |||
+ | < | ||
+ | # We need to add the beginning index (0), AND remove the last index | ||
+ | # (reduceat will automatically go to the end of the input array | ||
+ | >>> | ||
+ | array([3, 3, 4]) | ||
+ | >>> | ||
+ | >>> | ||
+ | 10 | ||
+ | >>> | ||
+ | [0, 3, 6] | ||
+ | |||
+ | # Compute the sums over the selected intervals with just one call | ||
+ | >>> | ||
+ | array([3. , 4.5, 8. ])</ | ||
/* | /* |
other/python/misc_by_jyp.txt · Last modified: 2024/11/04 15:01 by jypeter