python Module 4
python Module 4
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working with
ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very important.
Installation
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Output Summary
Array Type Example ndim Shape
0D (scalar) np.array(42) 0 ()
1D (vector) np.array([1, 2, 3]) 1 (3,)
2D (matrix) np.array([[1, 2, 3], [4, 5, 6]]) 2 (2, 3)
3D (tensor) np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) 3 (2, 2, 3)
Access Array Elements
import numpy as np
print(arr[0])
Output :
1
Access 2-D Arrays
import numpy as np
Output:
2
Access 3-D Arrays
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]
The second number represents the second dimension, which also contains two arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6
Slicing arrays
Slicing in python means taking elements from one given index to another given index.
print(arr[1:5])
Output:
[2,3,4,5]
STEP
Use the step value to determine the step of the slicing:
import numpy as np
print(arr[1:5:2])
Output:
[2,4]
Shape of an Array
import numpy as np
print(arr.shape)
Output:
(2,4)
Splitting an array
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
Output:
[array([1, 2]), array([3, 4]), array([5, 6])]
Searching Arrays
import numpy as np
x = np.where(arr == 4)
print(x)
Output:
(array([3, 5, 6]),)
Data Types in NumPy
NumPy has some extra data types, and refer to data types with one character, like i for integers, u for unsigned
integers etc.
Below is a list of all data types in NumPy and the characters used to represent them.
● i - integer
● b - boolean
● u - unsigned integer
● f - float
● c - complex float
● m - timedelta
● M - datetime
● O - object
● S - string
● U - unicode string
● V - fixed chunk of memory for other type ( void )