What is NumPy?
NumPy stands for Numerical Python. NumPy is a Python library used for working with arrays.
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.
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 than traditional Python lists.
NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate them very efficiently. Also
it is optimized to work with latest CPU architectures.
The source code for NumPy is located at this github repository [Link]
Installation of NumPy
In [1]: pip install numpy
Requirement already satisfied: numpy in c:\users\user\anaconda3\lib\site-packages (1.20.3)
Note: you may need to restart the kernel to use updated packages.
In [7]: import numpy as np
print(np.__version__)
1.20.3
NumPy First Example
In [4]: import numpy
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
[1 2 3 4 5]
In [8]: #type(): This built-in Python function tells us the type of the object passed to it.
type(arr)
[Link]
Out[8]:
In [17]: # 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
arr = [Link]((1, 2, 3, 4, 5))
print(arr)
[1 2 3 4 5]
Dimensions in Arrays
In [29]: #0-D array
arr0 = [Link](42)
print(arr0)
#1-D array
arr1 = [Link]([1, 2, 3, 4, 5])
print(arr1)
#2-D array
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print(arr2)
#3-D array
arr3 = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr3)
42
[1 2 3 4 5]
[[1 2 3]
[4 5 6]]
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
In [23]: #Check number of dimensions the arrays object has
print([Link])
print([Link])
print([Link])
print([Link])
0
1
2
3
NumPy Array Indexing
You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element
has index 0, and the second has index 1 etc.
In [34]: arr = [Link]([1, 2, 3, 4])
print('first element:', arr[0])
print('second element:',arr[1])
arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])
print('5th element on 2nd row: ', arr[1, 4])
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print('Element:', arr[0, 1, 2])
first element: 1
second element: 2
2nd element on 1st row: 2
5th element on 2nd row: 10
Element: 6
In [41]: # NumPy Negative indexing
arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
arr = [Link](['apple', 'banana', 'cherry'])
print([Link])
#arr = [Link](['a', '2', '3'], dtype='i')
#Change data type from float to integer
arr = [Link]([1.1, 2.1, 3.1])
newarr = [Link](int)
print(newarr)
print([Link])
Last element from 2nd dim: 10
[5 6]
<U6
[1 2 3]
int32
NumPy Array Slicing
We can also define the step, like this: [start:end:step]. If we don't pass start its considered 0 If we don't pass end its considered length of
array in that dimension If we don't pass step its considered 1
In [42]: #From the second element, slice elements from index 1 to index 4 (not included):
arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])
#From both elements, return index 2:
arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])
#From both elements, slice index 1 to index 4 (not included), this will return a 2-D array
arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])
[7 8 9]
[3 8]
[[2 3 4]
[7 8 9]]
In [1]: #Get the Shape of an Array
arr = [Link]([[1, 2, 3, 4], [5, 6, 7, 8]])
print([Link])
#Reshaping arrays
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = [Link](4, 3)
print(newarr)
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = [Link](2, 3, 2)
print(newarr)
#Flattening array means converting a multidimensional array into a 1D array.
arr = [Link]([[1, 2, 3], [4, 5, 6]])
newarr = [Link](-1)
print(newarr)
(2, 4)
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]
[1 2 3 4 5 6]
Iterating Arrays
Iterating means going through elements one by one.
In [4]: arr = [Link]([1, 2, 3])
for x in arr:
print(x)
arr = [Link]([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)
arr = [Link]([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)
#Iterating Arrays Using nditer()
arr = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
for x in [Link](arr):
print(x)
1
2
3
[1 2 3]
[4 5 6]
1
2
3
4
5
6
Joining and Splitting NumPy Arrays
Joining means putting contents of two or more arrays in a single array. In NumPy we join arrays by axes.
In [5]: arr1 = [Link]([[1, 2], [3, 4]])
arr2 = [Link]([[5, 6], [7, 8]])
arr = [Link]((arr1, arr2), axis=1)
print(arr)
arr = [Link]([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
[[1 2 5 6]
[3 4 7 8]]
[array([1, 2]), array([3, 4]), array([5, 6])]
In [ ]: #You can search an array for a certain value, and return the indexes that get a match.
arr = [Link]([1, 2, 3, 4, 5, 4, 4])
x = [Link](arr == 4)
print(x)
y = [Link](arr%2 == 0)
print(y)
#sorting an array
arr = [Link]([3, 2, 0, 1])
print([Link](arr))
arr = [Link]([[3, 2, 4], [5, 0, 1]])
print([Link](arr))
Filtering Arrays
Getting some elements out of an existing array and creating a new array out of them is called filtering. In NumPy, you filter an array using a
boolean index list. If the value at an index is True that element is contained in the filtered array, if the value at that index is False that
element is excluded from the filtered array.
In [6]: arr = [Link]([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x]
print(newarr)
arr = [Link]([41, 42, 43, 44])
filter_arr = arr > 42
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
[41 43]
[False False True True]
[43 44]
In [17]: #What is a Random Number?
#Random number does NOT mean a different number every time. Random means something that can not be predicted lo
from numpy import random
x = [Link](2)
print(x)
y = [Link](100)
print(y)
#Generate a 2-D array with 3 rows, each row containing 5 random integers from 0 to 100:
z = [Link](100, size=(3, 5))
print(z)
x = [Link]([3, 5, 7, 9])
print(x)
#Probability Density Function: A function that describes a continuous probability. i.e. probability of all valu
x = [Link]([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(10))
print(x)
[0.61497144 0.06722594]
50
[[97 18 9 44 59]
[53 9 25 89 77]
[60 96 72 52 49]]
9
[5 7 7 7 7 3 3 7 5 7]
In [19]: #Random Permutations of Elements
#The shuffle() method makes changes to the original array.
from numpy import random as rn
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
[Link](arr)
print(arr)
#The permutation() method returns a re-arranged array (and leaves the original array un-changed).
arr = [Link]([1, 2, 3, 4, 5])
print([Link](arr))
[4 1 5 3 2]
[4 3 2 1 5]
Universal Functions
universal funcs are used to implement vectorization in NumPy which is way faster than iterating over elements. Converting iterative
statements into a vector based operation is called vectorization. ufuncs also take additional arguments, like:
where: boolean array or condition defining where the operations should take place. dtype: defining the return type of elements. out: output
array where the return value should be copied.
In [26]: x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = []
for i, j in zip(x, y):
[Link](i + j)
print(z)
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = [Link](x, y)
print(z)
print(type([Link]))
arr1 = [Link]([10, 11, 12, 13, 14, 15])
arr2 = [Link]([20, 21, 22, 23, 24, 25])
newarr = [Link](arr1, arr2)
print(newarr)
#Addition is done between two arguments whereas summation happens over n elements.
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([1, 2, 3])
newarr = [Link]([arr1, arr2])
print(newarr)
newarr = [Link]([arr1, arr2], axis=1)
print(newarr)
newarr = [Link](arr1, arr2)
print(newarr)
newarr = [Link](arr1, arr2)
print(newarr)
newarr = [Link](arr1, arr2)
print(newarr)
arr2 = [Link]([3, 5, 6, 8, 2, 33])
newarr = [Link](arr1, arr2)
print(newarr)
[5, 7, 9, 11]
[ 5 7 9 11]
<class 'function'>
In [27]: arr = [Link](1, 10)
print(np.log2(arr))
print(np.log10(arr))
print([Link](arr))
[0. 1. 1.5849625 2. 2.32192809 2.5849625
2.80735492 3. 3.169925 ]
[0. 0.30103 0.47712125 0.60205999 0.69897 0.77815125
0.84509804 0.90308999 0.95424251]
In [ ]: