In the previous article, we discussed how to index the NumPy arrays. In this article, we discuss how to perform operations on NumPy arrays. Let’s get started.
Let’s create some sample arrays of the same size to play around with, the good thing with NumPy is that we can treat the arrays as vectors and we can perform operations on top of them just like with vectors.
For example, we can perform the addition of two arrays simply with the ‘+’ operator and it will do the element-wise addition of two arrays.
Let’s do the same thing using random numbers instead of 0’s and 1's.
So, we can perform this pointwise / element-wise addition, subtraction, multiplication, division(gives a warning if there is an element in the denominator with a value of 0)
We can also do some operations on a single array for instance to compute the exponential of each value, we use the ‘np.exp(array)’ function, we can compute the logarithmic of each data point in the array using ‘np.log(array)’ function
In a similar manner, we have ‘np.sin(array)’ , ‘np.cos(array)’ and other trigonometric functions
To compute the square root of each data point, we have ‘np.sqrt(array)’
All the functions available in the NumPy library are really useful and very efficiently implemented as they take into consideration how the arrays are stored and how these operations can be vectorized, their implementation is significantly faster than lists.
We can also perform operations using a scalar and the operation will be broadcasted to every data item for example to take the inverse of every data item in the array, we can just take the inverse of the array.
If we an array of zeros and we take its inverse, then it does not give an error:
In this case, the inversed array would have the keyword ‘inf’ denoting that the division, inverse led to an infinite value, it denotes that NumPy encountered a division by 0 case. We can check this by using ‘np.isinf()’ and give it a particular index value and this function return ‘True’ if the value at that index is infinite
We can pass the entire array to this function and it returns the boolean value for each data item in the array
There are multiple operations possible on the NumPy arrays and all the operations are performed very efficiently.