Calculate item frequency in an Numpy array
If we want to calculate the item frequency in a list, it is quite simple:
If we want to do the same thing with a Numpy array, it is slightly different:
Although Scipy provides a similar solution, if is not as fast as unique
in Numpy, the comp can be found at this Stackoverflow post.
Bonus:
numpy.unique
has two other optional parameters: return_index
and return_inverse
:
Conditional expression (ternary operator)
In python, a simple if ..., else ...
statement can construct a ternary operator:
In Numpy, such a ternary operator can be applied to arrays:
In this example, a random 4 by 4 matrix was constructed: with np.where, if the element in the original matrix is bigger than 0, it will be converted to 2; if smaller than 0, it will be converted to -2.
Another example: