- Python Dictionaries
- Comparison Operators in Python
- Logical Operators in Python
- Conditional Statements in Python
- For Loop in Python
- While Loop in Python
- How to loop over python dictionaries and Numpy arrays
- What is NumPy in Python
- ndarray - Methods and Data Type
- NumPy - Methods to Create Arrays
- Python NumPy - Numerical Operations on Arrays
- Python NumPy - Indexing and Slicing Arrays
Python NumPy - Numerical Operations on Arrays
Arrays have a unique advantage over Python lists in that they allow you to perform element-wise operations without the need for a for loop. This makes computations very efficient specially while dealing with large data sets.
Suppose we have a list and we want to multiply all its elements by 3 (scalar). If we try to directly multiply it by three, it will just add the list elements three times, which is not what we wanted.
>>> a = [1,3,5] >>> a*3 [1, 3, 5, 1, 3, 5, 1, 3, 5] >>>
To get the right results, you will use the for-loop approach which would look as follows:
>>> a = [1,3,5] >>> b = [3*x for x in a] >>> b [3, 9, 15] >>>
Grouping these element-wise operations together, a process known as vectorization, allows NumPy to perform such computations much more rapidly as shown below:
>>> import numpy as np >>> a = np.array([1, 3, 5]) >>> b = a*3 >>> b array([ 3, 9, 15]) >>>
These vectorized operations are not just restricted to interactions between arrays and scalars. We can even perform fast element-wise operations between arrays. The following example shows element-wise subtraction of two arrays.
>>> a = np.array([10,15,18]) >>> b = np.array([4,5,6]) >>> c = a - b >>> c array([ 6, 10, 12]) >>>
When the shapes of the two arguments are not the same, but share a common shape dimension, the operation is broadcasted across the array. In other words, NumPy expands the arrays such that the operation becomes viable. This process is called broadcasting.
>>> b array([4, 5, 6]) >>> x= np.arange(6).reshape((2,3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> y=x*b >>> y array([[ 0, 5, 12], [12, 20, 30]]) >>>
There are broadcasting rules but we will discuss those in an advanced course on NumPy.
- Using NumPy array, create a vector with values ranging from 10 to 49
- Create a 3x3 matrix with values ranging from 0 to 8. Multiply all the elements of the matrix with a magnitude of 3.