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 revision Previous revision
Next revision Both sides next revision
other:python:misc_by_jyp [2022/02/21 14:47]
jypeter [numpy related stuff] Added np.unique example
other:python:misc_by_jyp [2022/02/21 15:15]
jypeter [numpy related stuff]
Line 230: Line 230:
 >>>​ vals >>>​ vals
 array([1. , 2. , 1. , 2. , 2. , 1.5, 1. , 1.5, 2. , 1.5]) array([1. , 2. , 1. , 2. , 2. , 1.5, 1. , 1.5, 2. , 1.5])
 +
 >>>​ np.unique(vals) >>>​ np.unique(vals)
 array([1. , 1.5, 2. ]) array([1. , 1.5, 2. ])
->>>​ np.unique(vals,​ return_counts=True) +>>> ​unique_vals,​ nb_unique = np.unique(vals,​ return_counts=True) 
-(array([1. , 1.5, 2. ])array([3, 3, 4])+>>>​ unique_vals 
->>>​ np.sort(vals) # Sorted copy, in order to check the result+array([1. , 1.5, 2. ]) 
 +>>>​ nb_unique 
 +array([3, 3, 4]) 
 + 
 +>>> ​sorted_vals = np.sort(vals) # Sorted copy, in order to check the result 
 +>>>​ sorted_vals
 array([1. , 1. , 1. , 1.5, 1.5, 1.5, 2. , 2. , 2. , 2. ])</​code>​ array([1. , 1. , 1. , 1.5, 1.5, 1.5, 2. , 2. , 2. , 2. ])</​code>​
  
 +=== Applying a ufunc over all the elements of an array ===
 +
 +There are all sorts of //ufuncs// (Universal Functions), and we will just use below ''​add''​ from the [[https://​numpy.org/​doc/​stable/​reference/​ufuncs.html#​math-operations|math operations]],​ applied on the arrays defined in [[#​finding_and_counting_unique_values|Finding and counting unique values]]
 +
 +<​code>#​ Get the sum of all the elements of '​vals'​
 +>>>​ np.add.reduce(vals)
 +15.5
 +>>>​ np.add.reduce(sorted_vals)
 +15.5
 +>>>​ vals.sum() # The usual and easy way to do it
 +15.5</​code>​
  
 /* /*
other/python/misc_by_jyp.txt · Last modified: 2024/04/19 12:02 by jypeter