28.numpy 1
NumPy stands for Numerical Python.
NumPy is a python library used for working with arrays.
NumPy is a Python library and is written partially in Python, but most of the parts that require fast computation are written in C or C++.
Why use NumPy?
In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster that traditional Python lists.
Arrays are very frequently used in data science, where speed and resources are very important.
NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate them very efficiently.
How to Use NumPy?
Numpy is an external library, so we need to install it uisng pip
pip install numpy
import numpy as np
Creating Arrays
The array object in NumPy is called ndarray
.
We can create Numpy ndarray
object by using the array()
function.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
>>> [1 2 3 4 5]
>>> <class 'numpy.ndarray'>
To create an ndarray
, we can pass a list, tuple or any array-like object into the array()
method, and it will be converted into an ndarray
.
Example
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
>>> [1 2 3 4 5]
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
Nested array are arrays that have arrays as their elements.
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
import numpy as np
arr = np.array(42)
print(arr)
>>> 42
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the basic arrays.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
>>> [1 2 3 4 5]
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix.
Example
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
>>> [[1 2 3]
[4 5 6]]
3-D Arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
Example
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
>>> [[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
Check Number of dimensions
NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.
Example
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
>>> 0
1
2
3
Higher Dimensional Arrays
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using the ndmin argument.
Example
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
>>> [[[[[1 2 3 4]]]]]
number of dimensions : 5
In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.
Access Array Elements
We can access an array element by referring to its index number.
To access elements from 2-D arrays we can use comma separated integers representing the dimension and the index of the element.
Example
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
>>> 1
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print(arr[0, 1])
>>> 2
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
>>> 6
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print(arr[1,-1])
>>> 10
NumPy Array Slicing
Slicing in python means taking elements from one given index to another given index.
We pass slice instead of index like [start:stop:step]
By default, start will be 0.
stop will be len of the array in that dimension.
step will be 1.
Use the minus operator to refer to an index from the end.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
>>> [5 6 7]
print(arr[:4])
>>> [1 2 3 4]
print(arr[-3:-1])
>>> [5 6]
print(arr[1:5:2])
>>> [2 4]
print(arr[::2])
>>> [1 3 5 7]
Slicing 2-D Arrays
First parameter represents rows, second paramater represents index in the rows.
Example
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])
>>> [7 8 9]
print(arr[0:2, 2])
>>> [3 8]
print(arr[0:2, 1:4])
>>> [[2 3 4]
[7 8 9]]
Special Arrays
-
To Generate an array
np.arange(0,10) >>> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) np.arange(0,11,2) >>> array([ 0, 2, 4, 6, 8, 10])
-
To Generate array with zeros
np.zeros(3) >>> array([0., 0., 0.]) np.zeros((2,5)) # first number of tuple represents rows, second number represents columns >>> array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]])
-
To Generate array with ones
np.ones(5) >>> array([1., 1., 1., 1., 1.]) np.ones((3,4)) >>> array([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]])
-
To Generate Identity matrix
The matrix with same number of rows and columns and having 1's in the diagonal elements and others as 0s is called Identity Matrix.
np.eye(4) # parameter represents the number of rows or columns >>> array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]])
-
To Generate one dimesional array with evenly spaced elements.
np.linspace(0,5,10) >>> array([0. , 0.55555556, 1.11111111, 1. 66666667, 2.22222222, 2.77777778, 3.33333333, 3.88888889, 4.44444444, 5. ])
First parameter represents start point, second parameter represents stop point, third parameter represents number of evenly spaced elements needed between start and stop points. Here stop point will be included as one of the element.