NumPy Basics
Introduction
NumPy is an opensource code library in python that is used to work with arrays. The full form of NumPy is Numerical Python. NumPy library contains several array objects and methods that can perform mathematical and logical operations on the arrays.
Installing and Importing NumPy
Before working with the NumPy library, we first have to install and import it in our scripts or jupyter notebooks.
To install the NumPy library in the python environment, we’ll use the python package manager pip.
pip install numpy 
Or, if we want to install it in an anaconda environment, we’ll install it using the conda package manager.
conda install numpy 
Next, we import it in our jupyter notebook or python script with an alias ‘np.’
import numpy as np 
Creating Arrays
With NumPy, we can easily create single and multidimensional arrays. There are various ways in Numpy to create and initialize arrays.
Using Python Lists
import numpy as np # Creating onedimensional arrays using lists array_1d = np.array([1, 2, 3, 4, 5]) # Creating twodimensional arrays using lists array_2d = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) # Creating threedimensional arrays using lists array_3d = np.array([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]) print("onedimensional array:\n", array_1d, "\n\n") print("twodimensional array:\n", array_2d, "\n\n") print("threedimensional array:\n", array_3d, "\n\n") 
Output
onedimensional array:
[[11 12 13 14 15]

Using Functions available in the NumPy Package
 Numpy.arange  This method creates an array with incrementing values. This function takes some parameters like start number, end number, incrementing step value, and datatype.
import numpy as np # creating an array with the first six natural numbers array1 = np.arange(6) print(array1, "\n") # creating an array with 2 unit difference between integers # the given array starts from 4 and ends on 16 array2 = np.arange(4, 16, 2) print(array2, "\n") # creating an array of float datatype numbers array3 = np.arange(4.2, 5, 0.2, dtype='float') print(array3, "\n") 
Output
[0 1 2 3 4 5] [ 4 6 8 10 12 14] [4.2 4.4 4.6 4.8] 
 Numpy.eye  We use the eye method to create 2Dimensional arrays in python. The parameters in this function are the rows and the columns of the matrix. The elements where row and column index are identical (i.e., i=j) are 1, and the rest are 0.
import numpy as np # creating a 2D array of 3x3 shape # if we give only one parameter, it constructs a square matrix of the given length array1 = np.eye(3) print(array1, "\n") # creating a 2D array with four rows and six columns array2 = np.eye(4, 5) print(array2, "\n") 
Output
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] [[1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.]] 
 Numpy.diag  To create a matrix with the elements along the diagonal, we use the diag function from the Numpy Library.
import numpy as np # The given elements will be filled in the main diagonal of the matrix array1 = np.diag([4, 5, 6, 7]) print(array1, "\n") # The given elements will be filled in the second right diagonal of the matrix array2 = np.diag([4, 5, 6], 2) print(array2, "\n") # The array3 will contain the diagonal elements of the given matrix array3 = np.diag(np.array([[1,2], [3,4]])) print(array3, "\n") 
Output
[[4 0 0 0] [0 5 0 0] [0 0 6 0] [0 0 0 7]] [[0 0 4 0 0] [0 0 0 5 0] [0 0 0 0 6] [0 0 0 0 0] [0 0 0 0 0]] [1 4] 
General Functions to create arrays
import numpy as np # creating arrays with all zeros using ndarray.zeros function # array with four rows and five columns array1 = np.zeros((4, 5)) print("Array 1:\n", array1, "\n") # array of 3 dimensions with two rows and two columns array2 = np.zeros((3, 2, 2)) print("Array 2:\n", array2, "\n") # creating arrays with all ones using ndarray.ones function # array with two rows and three columns array3 = np.ones((2, 3)) print("Array 3:\n", array3, "\n") # array of 4 dimensions with three rows and two columns array4 = np.ones((4, 3, 2)) print("Array 4:\n", array4, "\n") # creating arrays with random numbers between 0 and 1 using ndarray.random method # array with three rows and two columns array5 = np.random.rand(3, 2) print("Array 5:\n", array5, "\n") # array of 2 dimensions with two rows and three columns array6 = np.random.rand(2, 2, 3) print("Array 6:\n", array6, "\n") 
Output
Array 1: [[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]] Array 2: [[[0. 0.] [0. 0.]] [[0. 0.] [0. 0.]] [[0. 0.] [0. 0.]]] Array 3: [[1. 1. 1.] [1. 1. 1.]] Array 4: [[[1. 1.] [1. 1.] [1. 1.]] [[1. 1.] [1. 1.] [1. 1.]] [[1. 1.] [1. 1.] [1. 1.]] [[1. 1.] [1. 1.] [1. 1.]]] Array 5: [[0.45196711 0.99911633] [0.8508798 0.5950981 ] [0.97565596 0.38944378]] Array 6: [[[0.24686468 0.52307803 0.73543751] [0.20464146 0.1344177 0.57673931]] [[0.32332036 0.13353472 0.40851912] [0.55583298 0.43454808 0.63386697]]] 
Physical attributes of an Array
In terms of physical properties, each NumPy array has a shape, a size, and a dimensional value.
NOTE: We refer to the arrays in NumPy as ndarray (ndimensional array). It is a homogenous object in NumPy, which provides us with the methods and functions to operate on the arrays.
import numpy as np array_1d = np.array([1, 2, 3]) array_2d = np.array([[1, 2, 3, 4, 5, 6], [6, 7, 8, 9, 10, 11]]) array_3d = np.array([[[1, 2, 3, 4], [6, 7, 8, 9]], [[11, 12, 13, 14], [16, 17, 18, 19]]]) 
Dimension
To get the dimensions or the axes of the array, we use the ndim property of the ndarray class.
print(array_1d.ndim, "\n") print(array_2d.ndim, "\n") print(array_3d.ndim, "\n") 
Output
1 2 3 
Shape
The shape of the array is the number of elements stored in each dimension. A 2D array with three rows and four columns will have a shape of (3, 4). We use the shape property of the ndarray class to get the shape of an array.
print(array_1d.shape, "\n") print(array_2d.shape, "\n") print(array_3d.shape, "\n") 
Output
(3,) (2, 6) (2, 2, 4) 
Size
The size of the array is the total number of elements stored in the array. The size property of the ndarray class gives us the size of the array.
print(array_1d.size, "\n") print(array_2d.size, "\n") print(array_3d.size, "\n") 
Output
3 12 16 
Elementary functions on Arrays
Sort
There is a sort function in the ndarray class to sort the elements of an array.
import numpy as np # Using the sort function to sort the elements of the onedimensional array. array1 = np.array([12, 1, 60, 8, 100, 16]) sorted_array1 = np.sort(array1) print("Sorted Array:\n", sorted_array1, "\n") # Using the sort function to sort the elements of the twodimensional array array2 = np.array([[12, 4, 6], [1, 0, 34]]) sorted_array2 = np.sort(array2, axis=0) print("Column Sorted 2D Array:\n", sorted_array2, "\n") sorted_array3 = np.sort(array2, axis=1) print("Row Sorted 2D Array:\n", sorted_array3, "\n") 
Output
Sorted Array: [ 1 8 12 16 60 100] Column Sorted 2D Array: [[ 1 0 6] [12 4 34]] Row Sorted 2D Array: [[ 4 6 12] [ 0 1 34]] 
Unique
We can get the unique values from the array using the unique method of the ndarray class in NumPy.
import numpy as np array = np.array([12, 1, 60, 8, 100, 16, 12, 1, 50, 100, 3, 2, 40, 8, 110, 50, 45, 90, 31, 80]) unique_array = np.unique(array) print(unique_array, "\n") print("There are ", np.size(unique_array), " unique elements in the array") 
Output
[ 1 2 3 8 12 16 31 40 45 50 60 80 90 100 110] There are 15 unique elements in the array 
Reverse
To reverse an array, we can use the flip function of the ndarray class. The flip function reverses the elements of the specified axis.
import numpy as np # reversing a onedimensional array using the flip function array1 = np.array([2, 4, 6, 8, 10, 12]) rev_array1 = np.flip(array1) print("Reversed 1D Matrix:\n", rev_array1, "\n") array2 = np.array([[1, 3, 5, 7], [9, 11, 13, 15], [17, 19, 21, 23], [25, 27, 29, 31]]) # reversing the rows of a twodimensional array rev_rows_array2 = np.flip(array2, axis=0) print("Row reversed 2D Matrix:\n", rev_rows_array2, "\n") # reversing the columns of a twodimensional array rev_cols_array2 = np.flip(array2, axis=1) print("Column reversed 2D Matrix:\n", rev_cols_array2, "\n") # reversing the entire content of the Matrix rev_array2 = np.flip(array2) print("Reversed 2D Matrix:\n", rev_array2, "\n") 
Output
Reversed 1D Matrix: [12 10 8 6 4 2] Row reversed 2D Matrix: [[25 27 29 31] [17 19 21 23] [ 9 11 13 15] [ 1 3 5 7]] Column reversed 2D Matrix: [[ 7 5 3 1] [15 13 11 9] [23 21 19 17] [31 29 27 25]] Reversed 2D Matrix: [[31 29 27 25] [23 21 19 17] [15 13 11 9] [ 7 5 3 1]] 
Frequently Asked Questions
 What is the difference between a list and an array in Python?
A python list can contain different data types in a single list, whereas all the elements in an array are homogenous. When compared to a list, an array is faster and takes up less memory space.
 How to install NumPy and import it in python?
To install the NumPy library in our system, we use the python package installer PIP or conda if we use the Anaconda environment.
pip install numpy or conda install numpy installs the numpy library in our environment.
To import it into our script, we have to write the import keyword along with an alias import numpy as np.
 What is the rank of an array?
The rank of an array is determined by the number of axes or the number of dimensions of the array. So, for a onedimensional array, the rank will be one; for a twodimensional array, it will be two, and so on.
 How can I reshape the array?
In python, we can reshape any array with a simple syntax. The reshape() function takes the new dimensions (newshape) as the parameter and then changes the array’s shape without disturbing any values.
 What are the advantages of NumPy?
NumPy supports the OOPS approach. For instance, the ndarray is a class that contains several properties and functions to make changes in the array. Numpy is much faster than, and the code written using NumPy more closely resembles standard mathematical notation (making it easier, typically, to correctly code mathematical constructs).
Key Takeaways
Congratulations on making it this far. In this blog, we discussed a fundamental overview of the NumPy library.
We saw how to install and import NumPy in our python program. Then we discussed some methods to create arrays using NumPy. We learned how to identify the physical attributes of the array using NumPy, and lastly, we saw some essential functions to deal with arrays using NumPy.
If you are preparing for the upcoming Campus Placements, then don’t worry. Coding Ninjas has your back. Visit this link for a carefully crafted and designed course oncampus placements and interview preparation.
Comments
No comments yet
Be the first to share what you think