Mastering Python (90 Blogs) Become a Certified Professional

What is NumPy in Python – Introduction to NumPy – NumPy Tutorial

Last updated on Sep 22,2023 3.8K Views

Tanishqa Chaudhary
An intellectual brain with a strong urge to explore different upcoming technologies,... An intellectual brain with a strong urge to explore different upcoming technologies, learn about them, and share knowledge.

NumPy is becoming more popular and is being consumed in a variety of commercial systems. As a result, it’s essential to comprehend what this library is about to offer. NumPy is one of the most powerful Python libraries because of its syntax, which is compact, powerful, and expressive together at the same time. It enables users to manage data in vectors, matrices, and higher-dimensional arrays, and it is also utilized in the industry for array computing. This article will outline What is NumPy in Python and the core features of the NumPy library.

What is NumPy in Python?

NumPy (numerical Python) is a library that consists of multidimensional array objects and a set of functions for manipulating them. It’s one of the most used Python packages for scientific computing as it  allows you to perform mathematical and logical operations on arrays. NumPy is a Python scripting language.

History of NumPy

Travis Oliphant built NumPy in 2005 by heavily modifying Numeric and combining features from the competitor Numarray. Numeric, the predecessor to NumPy, was established in 1995 by Jim Hugunin with help from a number of other developers. Travis Oliphant, a NumPy developer, succeeded in bringing the community together behind a single array package, so he transferred Numarray’s functionality to Numeric and released NumPy 1.0 in 2006. Now we got to know What is NumPy in Python and about its history. Now lets get to know why do we use it.

Why is NumPy used in Python?

We have lists in Python that act as arrays, however they are slow to process.  NumPy aims to provide an array object that is up to 50 times faster than traditional Python lists. It may be used to conduct a wide range of array-based mathematical operations. It extends Python with advanced analytical structures that ensure fast computations with arrays and matrices, as well as a large library of high-level mathematical functions that work with these arrays and matrices. NumPy arrays, unlike lists, are kept in a single continuous location in memory, allowing programmes to access and manipulate them quickly.

Features of NumPy

Features of NumPy- What is NumPy in Python-Edureka
                                                                     Features of NumPy
  • High performance:

NumPy addresses the slowness problem partly by providing multidimensional arrays and functions and operators that operate efficiently on arrays.

  • Integrating code from C/C++, Fortran:

We can use the functions in NumPy to work with code written in other languages. We can hence integrate the functionalities available in various programming languages. 

  • Multidimensional container:

An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its shape, which is a tuple of N non-negative integers that specify the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray.

  • Broadcasting Function:

The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations. It is a very useful concept when we work with arrays of uneven shapes. It broadcasts the shape of smaller arrays according to the larger ones.

  • Additional linear algebra:

It has the capability to perform complex operations of the elements like linear algebra, Fourier transform, etc.

  • Work with varied data base:

We can work with arrays of different data types. We can use the dtype function to determine the data type and hence get a clear idea about the available data set.

Installation of NumPy in Python

NumPy is simple to install by entering a few commands on your terminal window, and it runs on Linux, MacOS, and Windows. Simply follow the instructions outlined below.

Step 1: Check the Python Version

You must first determine which Python version you have before installing NumPy. Most operating systems come with Python preloaded, with the exception of Windows, which requires manual installation.

Run the following command to see if you have Python 2.

python -V

For Python 3:

python3 -V

A version number should appear in the output on your terminal.

Step 2: Install Pip

Pip is a Python package manager that allows you to install and manage Python software packages. On most operating systems, Pip is not preloaded. As a result, you’ll need to install the package manager for the Python version you’re using. Install both Pip versions if you have both versions of Python. In Windows we setup like:

Download PIP get-pip.py

1. launch a command prompt. To do so, type cmd into the Windows search box and then click the icon.

2. Then, to get the get-pip.py file, use the following command:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Installing PIP on Windows:

python get-pip.py

Verify Installation:

pip help

Step 3: Install NumPy

Once the pip is installed, run the following command to install NumPy.

In Python2:

pip install numpy

In Python3:
pip3 install numpy

Successfully installed numpy versions would be shown as the output on your terminal.

Step 4: Verify  the NumPy Installation

Run the following command to check whether the NumPy has been installed and is now part of your Python packages.

 For Python2:

pip show numpy

For Python3:

pip3 show numpy

The output should validate that you have NumPy installed, as well as the version and location of the package.

Step 5: Import the NumPy Package

You may now import the package and give it an alias after installing NumPy.

To begin, type one of the following commands to move to python prompt:

python

Or 

python3

You may import the new package and give it an alias once you’re at the python or python3 prompt.

import numpy as np

NumPy – Data Types

Below figure describes the different data types used in NumPy. Theses data types are written as

numpy.datatype

NumPy – Data Types-What is NumPy in Python-Edureka
                                                                                                                                 NumPy – Data Types

 

Examples of NumPy

Example 1:

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

Output:

[1 2 3 4 6]

Example 2:


import numpy as np

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

print(a[2]) 

Output:

[ 9 10 11 12]

Example 3:

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


 Output:
6

Example 4:

import numpy as np
dt = np.dtype(np.int32)
print (dt)

Output:

int32

[1 2 3 4 6]

Operations using NumPy in Python

Arrays in NumPy

The basic object of NumPy is the homogeneous multidimensional array. It is the NumPy library’s primary data structure. An array is a matrix of values that provides information about the raw data, how to locate and interpret elements. It consists of a collection of elements that can be indexed in a variety of ways. A tuple of positive integers is used to index it.  Axes are dimensions in NumPy. The number of axes is referred to as rank. The array class in NumPy is known as ndarray. 

Creating an Array:

There are various ways to create arrays in NumPy. Lets understand with an example:

Example:

import numpy as np
a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:n", a)
b = np.array((1 , 3, 2))
print ("nArray created using passed tuple:n", b)
c = np.zeros((3, 4))
print ("nAn array initialized with all zeros:n", c)
d = np.full((3, 3), 6, dtype = 'complex')
print ("nAn array initialized with all 6s.""Array type is complex:n", d)
e = np.random.random((2, 2))
print ("nA random array:n", e)
f = np.arange(0, 30, 5)
print ("nA sequential array with steps of 5:n", f)
g = np.linspace(0, 5, 10)
print ("nA sequential array with 10 values between""0 and 5:n", g)
arr = np.array([[1, 2, 3, 4],[5, 2, 4, 2],[1, 2, 0, 1]])
newarr = arr.reshape(2, 2, 3)
print ("nOriginal array:n", arr)
print ("Reshaped array:n", newarr)
arr = np.array([[1, 2, 3], [4, 5, 6]])
flarr = arr.flatten()
print ("nOriginal array:n", arr)
print ("Fattened array:n", flarr)

Output:

arrays in NumPy- Edureka      arrays in NumPy(2)- Edureka

Array Indexing:

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. For example

 import numpy 
arr = np.array([1, 2, 3, 4])
print(arr[0])

Output:

1

Array Slicing:

Slicing in python means taking elements from one given index to another given index. For example:

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

Output:

[2 3 4 5]

Basic functions used in array:

Basic function-What is NumPy in Python-Edureka

NumPy – Mathematical Functions

Trigonometric Functions

Standard trigonometric functions in NumPy return trigonometric ratios for a given angle in radians. The arcsin, arcos, and arctan functions return the trigonometric inverse of the provided angle’s sin, cos, and tan. The results of these methods can be validated using the numpy.degrees() function, which converts radians to degrees.

Example:

 import numpy as np
 a = np.array([0,30,45,60,90]) 
 print ("Sine of different angles:")   
 print (np.sin(a*np.pi/180))   
 print ("n")      
 print ("Cosine values for angles in array:")   
 print (np.cos(a*np.pi/180))
 print ("n")   
 print ("Tangent values for given angles:")   
 print (np.tan(a*np.pi/180))   

Output:
Trignometric Function- What is NumPy in Python- Edureka
Functions for Rounding
This is a function that returns the value rounded to the precision specified. The function used here is
numpy.around(a,decimals)
Example:

import numpy as np
in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]
print ("Input array : n", in_array)
round_off_values = np.round_(in_array)
 print ("nRounded values : n", round_off_values)   
 in_array = [.53, 1.54, .71]   
 print ("nInput array : n", in_array)   
 round_off_values = np.round_(in_array)   
 print ("nRounded values : n", round_off_values)   
 in_array = [.5538, 1.33354, .71445]   
 print ("nInput array : n", in_array)   
 round_off_values = np.round_(in_array, decimals = 3)   
 print ("nRounded values : n", round_off_values)   

Output:

Rounding Functions- Edureka

NumPy – Statistical Functions

NumPy offers a number of helpful statistical functions for determining the minimum, maximum, percentile standard deviation and variance, and so on from the elements in an array.The functions are as follows:

numpy.amin() and numpy.amax()numpy.amin() and numpy.amax()

Example:

 import numpy as np 
 a = np.array([[3,7,5],[8,4,3],[2,4,9]])
 print ("Our array is:")
 print (a)
 print ("n")
 print ("Applying amin() function:") 
 print (np.amin(a,1)) 
 print ("n")
 print ("Applying amin() function again:") 
 print (np.amin(a,0)) 
 print ("n") 
 print ("Applying amax() function:") 
 print (np.amax(a)) 
 print ("n") 
 print ("Applying amax() function again:") 
 print (np.amax(a, axis = 0)) 

Output:

Statistical Function- Edureka

Applications of NumPy in Python

  • NumPy optimizes and simplifies numerous mathematical processes commonly used in scientific computing, such as:
    • Multiplication of vectors
    • Multiplication of Matrix-Matrix and Matrix-Vector
    • Vector and matrix element-wise operations (i.e., adding, subtracting, multiplying, and dividing by a number )
    • Comparisons between elements or arrays
    • Applying functions to a vector/matrix element by element ( like pow, log, and exp)
    • NumPy contains a large number of Linear Algebra operations.
    • linalg
    • Statistics, reduction, and much more
  • It maintains minimal memory
  • It is used in machine learning

 

So, that was a brief overview of the NumPy library, where we learnt about NumPy, its history, why it’s important, its features, and how to use it. I hope this has clarified things for you in a clear and understandable manner. Try it out for yourself to improve your NumPy knowledge. If you want to become a Data Scientist, and learn the Data science skills from Top Data Scientists from around the world, do checkout Edureka’s Data Science with Python Course, and give wings to your career!

Upcoming Batches For Data Science with Python Certification Course
Course NameDateDetails
Data Science with Python Certification Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Data Science with Python Certification Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is NumPy in Python – Introduction to NumPy – NumPy Tutorial

edureka.co