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.

  1. Create an array with seven random integers from -3 to 3 with a seed of 42:
    >>> 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.

  2. Apply the at() method of the sign() 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 how to create random integers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset