What is NumPy?
NumPy is Python’s fundamental scientific computing library. With NumPy we can
- Create multidimensional arrays
- Fast mathematical operations
- Integrate with lower level languages like C or C++
- Linear Algebra and Fourier transform
- Python’s solution for vectorization
Why use NumPy
Take an example where we need to calculate speeds of different cars. To calculate speeds we will need to use this formula
Speeds = Distances / Times
Let’s say we have Distanced and Times in lists and now we need to calculate speeds
1 2 3 4 5 6 7 8 |
distances = [10, 20, 30, 40] times = [1.0, 0.9, 0.8, 0.6] speeds = [] for i in range(len(distances)): speeds.append(distances[i]/times[i]) speeds |
The above code will output following result
[10.0, 22.22222222222222, 37.5, 66.66666666666667]
Another way of writing above code will be to use the List comprehension as given below
1 |
[distances[i]/times[i] for i in range(len(distances))] |
This will output
[10.0, 22.22222222222222, 37.5, 66.66666666666667]
If we use NumPy to achieve the above it can be as simple as speeds = distances / times
How to convert Python List to NumPy Array
- First of all, we will import NumPy library to our programme by using import
- Now we will convert Python list to numpy array using the array(name of list) method
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# import numpy library as np import numpy as np # Create two lists distances = [10, 20, 30, 40] times = [1.0, 0.9, 0.8, 0.6] # convert python lists to a NumPy array using np.array distances = np.array(distances) times = np.array(times) speeds = distances/times print(speeds) |