NumPy Basics

NumPy Basics

Prerequisites : Basic understanding of arrays and that's it

In the world of programming, we need to work with arrays majority of the time. NumPy enhances computational efficiency by providing optimized functions and operations for array computing in Python.

NumPy, short for Numerical Python is a Python library which provides an extensive collection of functions and operations for working with multidimensional arrays and matrices. These arrays are the building blocks for most scientific computing tasks, offering a convenient and efficient way to manipulate large datasets and perform complex mathematical operations.

Let's delve into NumPy by code part:

At first, we need Google Colab to run the python codes. Make a new notebook and here you go.

Type this code there and see the output:

import numpy as np
arr0 = np.array([1, 2, 3, 4, 5])
print(arr0)
[1 2 3 4 5]

We have imported numpy as np alias or another name and created a 1D array.

import numpy as np
arr1 = np.array([1, 5, 9, 10])
print(arr1.ndim)

The above code will show the dimension of an array as the output.

1
import numpy as np
arr2 = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
print(arr2)
print(arr2.ndim)
[[1 2 3 4]
 [5 6 7 8]]
2

In the above code, we have created a 2D array like the same process.

import numpy as np
arr2 = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
arr3 = np.array(arr2, ndmin = 3)
print(arr3)
[[[1 2 3 4]
  [5 6 7 8]]]

Above code shows the conversion of a 2D array to 3D array in the result depending upon the value of ndmin.

import numpy as np
arr4 = np.array([[1, 2, 6],[8, 10, 12]])
print(arr4.shape)
(2, 3)

The above code shows the shape of the array means the number of rows and the number of columns respectively.

import numpy as np
arr4 = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print(arr4[1][1:4])
[7 8 9]

The above example shows the slicing of a 2D array where we have taken the 1st index element array and sliced from 1st index to 3rd index.

import numpy as np
arr4 = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print(arr4.dtype)
int64

The above code shows the datatype of the 2D array.

import numpy as np
new3 = np.array([2,6,8,10])
convert_new3 = new3.astype('f')
print(convert_new3)
[ 2.  6.  8. 10.]

astype function is used to change a datatype to another datatype. ( Ex. 'f' for float, 'i' for integer ).

a1 = np.array([1, 2, 4, 8])
copy = a1.copy()
a1[1] = 11
print(a1)
print(copy)
array([ 1, 11,  4,  8])
array([1, 2, 4, 8])