Using arrays and scalars

In this section, we are going to look at various arithmetic operations on arrays using numpy. For that, first we will create a multidimensional array, as follows:

student@ubuntu:~$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> from __future__ import division
>>> arr = np.array([[4,5,6],[7,8,9]])
>>> arr
array([[4, 5, 6],
[7, 8, 9]])
>>>

Here, we imported the numpy module to use the numpy functionality, and then we imported the __future__ module that will take care of floats. After that, we created a two dimensional array, arr, to perform various operations on it.

Now, let's look at some arithmetic operations on arrays. First, we will study the multiplication of arrays, as shown here:

>>> arr*arr
array([[16, 25, 36],
[49, 64, 81]])
>>>

In the preceding multiplication operation, we multiplied the arr array twice to get a multiplied array. You can also multiply two different arrays.

Now, we are going to look at a subtraction operation on an array, as shown here:

>>> arr-arr
array([[0, 0, 0],
[0, 0, 0]])
>>>

As shown in the preceding example, we just use the  - operator to do the subtraction of two arrays. After the subtraction of the arrays, we got the resultant array, as shown in the preceding code.

Now we are going to look at arithmetic operations on arrays with scalars. Let's look at some operations:

>>> 1 / arr
array([[0.25 , 0.2 , 0.16666667],
[0.14285714 , 0.125 , 0.11111111]])
>>>

In the preceding example, we divided 1 by our array and got the output. Remember, we imported the __future__ module, which is actually useful for such operations, to take care of float values in the array.

Now we will look at the exponential operation on the numpy array, as shown here:

>>> arr ** 3
array([[ 64, 125, 216],
[343, 512, 729]])
>>>

In the preceding example, we took a cube of our array and it gave the output as the cube of each value in the array.

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

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