Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Installing and Importing NumPy
3.
Creating Arrays
3.1.
Using Python Lists
3.2.
Using Functions available in the NumPy Package
3.3.
General Functions to create arrays
4.
Physical attributes of an Array
4.1.
Dimension
4.2.
Shape
4.3.
Size
5.
Elementary functions on Arrays
5.1.
Sort
5.2.
Unique
5.3.
Reverse
6.
 
7.
 
8.
 
9.
 
10.
 
11.
 
12.
 
13.
 
14.
 
15.
Frequently Asked Questions
16.
Key Takeaways
Last Updated: Mar 27, 2024

NumPy Basics

Introduction

NumPy is an open-source 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 one-dimensional arrays using lists
array_1d = np.array([12345])

# Creating two-dimensional arrays using lists
array_2d = np.array([[12345],
                    [678910]])

# Creating three-dimensional arrays using lists
array_3d = np.array([[[12345], [678910]],
                    [[1112131415], [1617181920]]])
                    
print("one-dimensional array:\n", array_1d, "\n\n")
print("two-dimensional array:\n", array_2d, "\n\n")
print("three-dimensional array:\n", array_3d, "\n\n")

Output

one-dimensional array:
[1 2 3 4 5]


two-dimensional array:
[[ 1  2  3  4  5]
[ 6  7  8  9 10]]


three-dimensional array:
[[[ 1  2  3  4  5]
 [ 6  7  8  9 10]]

[[11 12 13 14 15]
 [16 17 18 19 20]]]

 

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(4162)
print(array2, "\n")

# creating an array of float datatype numbers
array3 = np.arange(4.250.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 2-Dimensional 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 2-D 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 2-D array with four rows and six columns
array2 = np.eye(45)
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([4567])
print(array1, "\n")

# The given elements will be filled in the second right diagonal of the matrix
array2 = np.diag([456], 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((45))
print("Array 1:\n", array1, "\n")

# array of 3 dimensions with two rows and two columns
array2 = np.zeros((322))
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((23))
print("Array 3:\n", array3, "\n")

# array of 4 dimensions with three rows and two columns
array4 = np.ones((432))
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(32)
print("Array 5:\n", array5, "\n")

# array of 2 dimensions with two rows and three columns
array6 = np.random.rand(223)
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 (n-dimensional 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([123])

array_2d = np.array([[123456],
                    [67891011]])

array_3d = np.array([[[1234], [6789]],
                    [[11121314], [16171819]]])

 

 

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 2-D 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,) 

(26

(224

 

 

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 one-dimensional array.
array1 = np.array([12160810016])
sorted_array1 = np.sort(array1)
print("Sorted Array:\n", sorted_array1, "\n")

# Using the sort function to sort the elements of the two-dimensional array
array2 = np.array([[1246], [1034]])
sorted_array2 = np.sort(array2, axis=0)
print("Column Sorted 2-D Array:\n", sorted_array2, "\n")

sorted_array3 = np.sort(array2, axis=1)
print("Row Sorted 2-D Array:\n", sorted_array3, "\n")

 

 

Output

Sorted Array:
1   8  12  16  60 100

Column Sorted 2-D Array:
[[ 1  0  6]
[12  4 34]] 

Row Sorted 2-D 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([1216081001612150100324081105045903180])
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 one-dimensional array using the flip function
array1 = np.array([24681012])
rev_array1 = np.flip(array1)
print("Reversed 1-D Matrix:\n", rev_array1, "\n")

array2 = np.array([[1357],
                [9111315],
                [17192123],
                [25272931]])
                
# reversing the rows of a two-dimensional array
rev_rows_array2 = np.flip(array2, axis=0)
print("Row reversed 2-D Matrix:\n", rev_rows_array2, "\n")

# reversing the columns of a two-dimensional array
rev_cols_array2 = np.flip(array2, axis=1)
print("Column reversed 2-D Matrix:\n", rev_cols_array2, "\n")

# reversing the entire content of the Matrix
rev_array2 = np.flip(array2)
print("Reversed 2-D Matrix:\n", rev_array2, "\n")

 

 

Output

Reversed 1-D Matrix:
[12 10  8  6  4  2

Row reversed 2-D Matrix:
[[25 27 29 31]
[17 19 21 23]
9 11 13 15]
1  3  5  7]] 

Column reversed 2-D Matrix:
[[ 7  5  3  1]
[15 13 11  9]
[23 21 19 17]
[31 29 27 25]] 

Reversed 2-D Matrix:
[[31 29 27 25]
[23 21 19 17]
[15 13 11  9]
7  5  3  1]] 

 

 

 

 

 

 

 

 

 

 

 

Must Read Python List Operations

Frequently Asked Questions

  1. 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.
     
  2. 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.
     
  3. 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 one-dimensional array, the rank will be one; for a two-dimensional array, it will be two, and so on.
     
  4. 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.
     
  5. 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.

Check out this problem - Search In Rotated Sorted Array

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 on-campus placements and interview preparation.

Live masterclass