Numpy is the numerical computing library in Python, that provides wonderful support for creating and manipulating arrays.
You can install numpy if it is not already installed by running the following code:
!python3 -m pip install numpy
Requirement already satisfied: numpy in /home/anand/github/anandology/isi-fcp/.venv/lib/python3.12/site-packages (2.1.2)
[notice] A new release of pip is available: 24.1.2 -> 24.2
[notice] To update, run: pip install --upgrade pip
Let’s get started by importing the numpy module.
import numpy as np
np.__version__
'2.1.2'
Introduction to Numpy Arrays
Let’s start with creating an array.
x = np.array([1, 2, 3, 4, 5])
x
array([1, 2, 3, 4, 5])
Numpy allows vector operations on arrays. These operations that work on every element of the array.
x +10
array([11, 12, 13, 14, 15])
x*x
array([ 1, 4, 9, 16, 25])
Multi-dimentional arrays
Numpy supports n-dimentional arrays.
d = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
d
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
d +10
array([[11, 12, 13, 14],
[15, 16, 17, 18]])
d*d
array([[ 1, 4, 9, 16],
[25, 36, 49, 64]])
It supports many mathematical functions to work with 2-d arrays or matrices.
np.transpose(d)
array([[1, 5],
[2, 6],
[3, 7],
[4, 8]])
d1 = np.transpose(d)
np.dot(d, d1)
array([[ 30, 70],
[ 70, 174]])
It also suppports even higher dimentional arrays, though we may not use to them in this course.
The array x is a one dimentional array and d is a two dimentional array.
You may be surprised why x.shape is shown as (5,) instead of (5). In python the parenthesis are used both for grouping and to represent tuples (kind-of read-only lists). The value of (5) is 5 because it is considered as grouping. It is just like (2 + 3). However if we want to represent a tuple of size 1, the only way is to include a comma to force to treat that as a tuple.
x.dtype
dtype('int64')
The elements of x are are 64-bit integers.
x2 = np.array([0.1, 0.2, 0.3])
x2.dtype
dtype('float64')
When we use decimal numbers, it used a dtype of float64.
Creating Arrays
While we can create arrays by giving all the elements, like we did in the example above, it is not practical to create large arrays like that. Numpy has utilities to create arrays.
# create 10 zerosnp.zeros(10)
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
# create 10 onesnp.ones(10)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
# range of numbers from 0 to 1 in steps of 0.1# please note that the end is not includednp.arange(0, 1, 0.1)