Time for action – fancy indexing in-place for ufuncs with the at() method
To demonstrate how the at()
method works, start a Python or IPython shell and import NumPy. You should know how to do this by now.
- Create an array with seven random integers from
-3
to3
with a seed of42
:>>> a = np.random.random_integers(-3, 3, 7) >>> a array([ 1, 0, -1, 2, 1, -2, 0])
When we talk about random numbers in programming, we usually talk about pseudo-random numbers (see https://www.khanacademy.org/computing/computer-science/cryptography/crypt/v/random-vs-pseudorandom-number-generators). The numbers appear random, but in fact are calculated using a seed.
- Apply the
at()
method of thesign()
universal function to the fourth and sixth array elements:>>> np.sign.at(a, [3, 5]) >>> a array([ 1, 0, -1, 1, 1, -1, 0])
What just happened?
We used the at()
method to select array elements and performed an in-place operation—determining the sign. We also learned...