It is a Python library that supports large, multi-dimensional arrays & matrices and a wide range of mathematical functions to operate on these arrays. It was created by Travis Oliphant in 2005. It is designed to be fast and efficient for performing numerical computations & mathematical functions for operations such as;
- Array manipulation
- Linear Algebra
- Fourier Transform
- Random Number Generation, and many more.
To utilize NumPy in our code, we need to import it by adding the following line at the beginning of the script:
import numpy as np
1D Arrays
It's the same as accessing any array element. We can access any array element through its index number. The indexes in Python start with 0.
arr = np.array([1,2,3,4])
2D Arrays
To access 2D arrays, comma-separated integers representing the dimension & the index of the element are used. The dimension represents the rows & index represents the column.
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
To access any element from say, 3rd element from 2nd row:
print(arr[1,2])
8
3D Arrays
To access 3D arrays, we can further extend the comma-separated integers.
arr = np.array([[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]])
To access 3rd element of the 2nd array of the 1st array:
print(arr[0,1,2])
6
0 => 1st dimension that contains 2 arrays: [[1,2,3], [4,5,6]] & [[7,8,9], [10,11,12]], with 0 it'll choose [[1,2,3], [4,5,6]]
1 => 2nd dimension that contains 2 arrays: [1,2,3] & [4,5,6], with 1 it'll choose [4,5,6]
2 => 3rd dimensions that contains 3 values: 4,5 & 6, with 2 it'll choose 6
Negative Indexing
Using negative indexing to access the array elements from the end.
Slicing in Python refers to accessing elements from the array based on its index.
arr[start:end]
arr[start: end :step]
- If no "start", it's considered as 0.
- If no "end", it's considered as the length of the array in that dimension.
- If no "step", it's considered as 1.
Negative Slicing
Using the minus operator to refer to an index from the end.
arr[-3:-1]
It'll access array elements from the 3rd last to the 2nd last.
Slicing 2D Arrays
From the 2nd element, slicing elements from index 1 to index 4 (not included).
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
arr[1, 1:4]
O/p:
[7 8 9]
Common Python data types:
- strings => "ABCD"
- integer => 1,2,3,-1,-2,-3
- float => 1.2,42.42
- boolean => True/False
- complex => 1.0+2.0j, 1.5+2.5j
NumPy Data types and the characters used to represent them.
- i => integer
- b => boolean
- u => unsigned integer
- f => float
- c => complex float
- m => time delta
- M => datetime
- O => object
- S => string
- U => unicode string
- V => fixed chunk of memory of other type (void)
Checking Data type of an Array.
arr.dtype
Creating Arrays with a defined Data type.
arr = np.array([1,2,3,4], dtype='S')
Converting data type of an existing array.
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
Output:
[1 2 3]
int32