11.NUMPY Lab File (R20)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 105

1

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY

2022-2023 Ist Semester


LABORATORY MASTER MANUAL
of
Applications of Python-Numpy LAB

Prepared by
SkAhmed Mohiddin
Assistant Professor
for
II B.Tech
CSE(R20)

DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

1
2

INDEX
Page
S.NO DESCRIPTION
No.
1 Institute Vision and Mission 3
2 Department Vision and Mission 4
3 PO’s 5
4 PSO’s, PEO’s 7
5 Details of associated course(s) and CO’s 8
6 CO/ PO/ PSO Mapping 8
7 CO/ PO/ PSO Justification 9
8 University / JNTUKSyllabus 10
9 List of Experiments 11
LIST OF EXPERIMENTS
NumPy Installation using different scientific python distributions
10 12
(Anaconda, Python (x,y), WinPython, Pyzo)
NumPy Basics (np.array, np.arrange, np.linespace, np.zeros, np.ones,
11 np.random.random, np.empty) 18
Arrays ( array.shape, len(array), array.ndim, array.dtype,
12 32
array.astype(type), type(array))
Array Manipulation (np.append, np.insert, np.resize, np.delete,
13 39
np.concatenate, np.vstack, np.hstack)
Mathematical Operations ( np.add, np.substract, np.divide,
14 np.multiply, np.sqrt, np.sin, np.cos, np.log, np.dot, np.roots) , 57
Statistical Operations( np.mean, np.median, np.std, array.corrcoef( ) )
15 NumPy data types 82
16 NumPy ndarray 87
17 NumPy String Operations 90
18 NumPy Financial functions 103
19 NumPy Functional Programming 125

2
3

INSTITUTE VISION AND MISSION

Vision
To emerge as a premier engineering institution in rural India imparting values based education for
socio-economic upliftment.
Mission
IM1: Provide the most creative learning environment for Technical Excellence of stakeholders
IM2: Promote industry-institute interaction for skill enhancement and to meet the industry needs
IM3: Create an environment to the stakeholders to be good citizens with integrity and morality.
IM4: Committed to improve technical excellence, ethical values continuously

Principal

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


4

DEPARTMENT VISION AND MISSION

Vision

To be a reputed center for quality computer science and engineering education by fulfilling the ever
changing needs of industry and society.

Mission
DM 1: To provide knowledge and skills required for industry.
DM2: To conduct training and activities with stake holder involvement
DM 3: To provide a learning ambience for enhancing innovation, professional and interpersonal
skills

Head of the Department

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


5

PROGRAM OUTCOMES (POs)

PO1 Engineering Knowledge: Apply knowledge of mathematics and science, with fundamentals of
Computer Science and Engineering to be able to solve complex engineering problems related to CSE.
PO2 Problem Analysis: Identify, Formulate, review research literature and analyze complex engineering
problems related to Computer Science and Engineering and reaching substantiated conclusions using first
principles of mathematics, natural sciences and engineering sciences
PO3 Design/Development of solutions: Design solutions for complex engineering problems related to
Computer Science and Engineering and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety and the cultural societal and
environmental considerations
PO4 Conduct Investigations of Complex problems: Use research based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5 Modern Tool Usage: Create, Select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to computer science related complex
engineering activities with an understanding of the limitations
PO6 The Engineer and Society: Apply Reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the Computer
Science and Engineering professional engineering practice
PO7 Environment and Sustainability: Understand the impact of the Computer Science and Engineering
professional engineering solutions in societal and environmental contexts and demonstrate the knowledge
of, and need for sustainable development
PO8 Ethics: Apply Ethical Principles and commit to professional ethics and responsibilities and norms of
the engineering practice
PO9 Individual and Team Work: Function effectively as an individual and as a member or leader in
diverse teams and in multidisciplinary Settings
PO10 Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large such as able to comprehend and with write effective reports and design
documentation, make effective presentations and give and receive clear instructions.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


6

PO11 Project Management and Finance: Demonstrate knowledge and understanding of the engineering
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multi-disciplinary environments
PO12 Life-Long Learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning the broadest context of technological change.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


7

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


8

DETAILS OF ASSOCIATED COURSES


COURSE OUT COMES:
Course Name: Applications of Python-Numpy Lab
DETAILS OF ASSOCIATED COURSES
COURSE OUT COMES:
Course Name: Applications of Python-Numpy Lab
C219.1 Explain how data is collected, managed and stored for processing
C219.2 Understand the workings of various numerical techniques, different descriptive
C219.3 measures of Statistics, correlation and regression to solve the engineering problems
C219.4 Understand how to apply some linear algebra operations to n-dimensional arrays

MAPPING LEVELS:
Correlation levels 1, 2 or 3 as defined below:
1: Slight (Low) 2: Moderate (Medium) 3: Substantial (High)
CO/PO/PSO MAPPING
CO/ PS PS PS
PO/ P01 P02 P03 P04 P05 P06 P07 P08 P09 P10 P11 P12 O1 O2 O3
PSO
C219.1 3 2 1 - - - - - - - - - 3 2
C219.2 2 2 1 - - - - - - - - 3 2
C219.3 2 2 1 - 3 - - - - - - - 3 3
C219.4 1 2 2 - 2 - - - - - - - 3 3

CO/PO/PSO JUSTIFICATION
CORRELATION
MAPPING LEVELS JUSTIFICATION
C219.1-PO1 3 Knowing all the basics in Numpy
C219.1-PO2 2 Identifying the problems while installing Numpy
C219.2-PO1 2 Knowing the fundamentals of array in Numpy
C219.2-PO2 3 Analyzing which type of array is usefull in Numpy
C219.2-PO3 3 Devoleping the solution involved in usage of array.
C219.3- PO1 2 Knowing how the mathematical operations applied in Numpy
C219.3 -PO2 2 Identifying the suitable data type in Numpy for the given problem
C219.3-PO3 3 Knowing how to apply statistical operations applied in Numpy
C219.3-PO5 2 Exportingthe new tools to process the data in Numpy
C219.4-PO1 2 Knowing the how ndarray is usefull Numpy
C219.4-PO2 2 Analyzing how a task can be solved in Numpy
C219.4-PO3 2 Devoleping the solutions using various data types available in
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
9

Numpy

II Year –ISEMESTER T P C
0 4 2
Applications of Python-Numpy Lab

Week 1:
1) NumPy Installation using different scientific python distributions( Anaconda,
Python(x,y), WinPython, Pyzo)
Week 2:
2) NumPy Basics (np.array, np.arrange, np.linespace, np.zeros, np.ones,
np.random.random, np.empty)
Week 3:
3) Arrays ( array.shape, len(array), array.ndim, array.dtype, array.astype(type),
type(array))
Week 4:
4) Array Manipulation (np.append, np.insert, np.resize, np.delete, np.concatenate,
np.vstack, np.hstack)
Week 5:
5) Mathematical Operations( np.add, np.substract, np.divide, np.multiply, np.sqrt, np.sin,
np.cos, np.log, np.dot, np.roots) , Statistical Operations( np.mean, np.median, np.std,
array.corrcoef( ) )
Week 6:
6) NumPy data types
Week 7:
7) NumPy ndarray
Week 8:
8) NumPy String Operations
Week 9:
9) NumPy Financial functions
Week 10:
10) NumPy Functional Programming

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


10

LIST OF EXPERIMENTS:
PO/PSO
S.No. Experiment Description CO Number
NumPy Installation using different PO1,PO2,PO3/
1 scientific python distributions( Anaconda, C219.1 PSO1,PSO3
Python(x,y), WinPython, Pyzo)
NumPy Basics (np.array, np.arrange, PO1,PO2,PO3/
2 np.linespace, np.zeros, np.ones, C219.1 PSO1,PSO3
np.random.random, np.empty)
Arrays ( array.shape, len(array), PO1,PO2,PO3 /
3 array.ndim, array.dtype, C219.3 PSO1,PSO3
array.astype(type),
type(array))
Array Manipulation (np.append, np.insert, PO1,PO2,PO3 /
4 np.resize, np.delete, np.concatenate, C219.3 PSO1,PSO3
np.vstack, np.hstack)
Mathematical Operations( np.add, PO1,PO2,PO3 /
np.substract, np.divide, np.multiply, PSO1,PSO3
np.sqrt, np.sin,
5 np.cos, np.log, np.dot, np.roots) , C219.1
Statistical Operations( np.mean,
np.median, np.std,
array.corrcoef( ))
PO1,PO2,PO3,PO5
6 NumPy data types C219.1
/ PSO1,PSO3
PO1,PO2,PO3,PO5
7 NumPy ndarray C219.3
/ PSO1,PSO3
PO1,PO2,PO3,PO5
8 NumPy String Operations C219.1
/ PSO1,PSO3
PO1,PO2,PO3,PO5
9 NumPy Financial functions C219.2
/ PSO1,PSO3
PO1,PO2,PO3,PO5
10 NumPy Functional Programming C219.4
/ PSO1,PSO3

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


11

1) NumPy Installation using different scientific python distributions (Anaconda, Python (x,y), WinPython,
Pyzo)
Anaconda
Anaconda is a Python distribution. Python distributions provide the Python interpreter, together with a list
of Python packages and sometimes other related tools, such as editors. To be more precise, Anaconda is not
limited to packaging Python packages, but initially emerged to cater for Python-based applications and
packages.
The packages provide by the Anaconda Python distribution include all of those that we need, and for that
reason we suggest to use Anaconda here.
A key part of the Anaconda Python distribution is Spyder, an interactive development environment for
Python, including an editor.
Installing NumPy
Before NumPy's functions and methods can be used, NumPy must be installed. Depending on which
distribution of Python you use, the installation method is slightly different.
Install NumPy on Anaconda
If you installed the Anaconda distribution of Python, NumPy comes pre-installed and no further installation
steps are necessary.
If you use a version of Python from python.org or a version of Python that came with your operating
system, the Anaconda Prompt and conda or pip can be used to install NumPy.
Install NumPy with the Anaconda Prompt
To install NumPy, open the Anaconda Prompt and type:
> conda install numpy
Type y for yes when prompted.
Install NumPy with pip
To install NumPy with pip, bring up a terminal window and type:
$ pip install numpy
This command installs NumPy in the current working Python environment.
Verify NumPy installation
To verify NumPy is installed, invoke NumPy's version using the Python REPL. Import NumPy and call
the .__version__ attribute common to most Python packages.
In [1]:
import numpy as np
np.version
Out[1]:
'1.16.4'
A version number like '1.16.4' indicates a successful NumPy installation.
Getting started with Pyzo

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


12

To get started with Pyzo, you need to install the Pyzo IDE (in which you write your code) and a Python
environment (in which you run your code).

Step 1: install the Pyzo IDE


Most users can select one of these:
 Windows: Pyzo installer (64bit)
 macOS: Pyzo dmg (macOS 10.13 High Sierra or higher)
 Linux: Pyzo tarball (build on Ubuntu 18.04, 64bit).
Otherwise, see all releases for more downloads (e.g. 32/64 bit Windows zipfiles, and older versions). Linux
users can also install Pyzo using Linux system packages. See the installation page for more information.

Step 2: install Python environment


To run Python code, you need a Python interpreter. Pyzo works with most Python interpreters. If you're not
sure what to use, don't worry, you can install multiple environments side-by-side, and use each one from
Pyzo. Just make sure to use Python 3 (not Python 2).
We recommend starting with either of these:
 The regular Python. Additional packages can be installed using  pip .
 The Anaconda distribution comes with a lot of scientific packages.
 The Miniconda distribution is a lighter version that starts with fewer packages. Additional packages
can be installed using  conda  or  pip .
We recommend installing in the default location, or at least a location that can be written to without admin
privileges, so that addtional packages can be installed.

Step 3: Configure Pyzo shell


In Pyzo you can configure one or more shells to target your Python environment(s). Pyzo is usually pretty
good at detecting any installed Python environments, and will try to guide you to selecting a suitable one.

Step 4: Install additional packages


Depending on you needs, you might need a few extra packages. In Pyzo's shell, type:
install requests
Hooray, you just installed a new package! For details see this guide. For scienctific computing, you may
want to install this set of the most important scientific packages (a.k.a. the scipy-stack):
install numpy scipy pandas matplotlib sympy pyqt

Further steps
You should now be set up to start coding! You can also learn more about using the IDE and about using
Python.

Updating

Pyzo and the Python environment can safely be updated/reinstalled independently from each-other.
Similarly, you can install multiple Python environments and use/manage them all via Pyzo. Individual
packages within a Python environment can be updated via  update package_name .

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


13

WINPYTHON
INSTALLING PYTHON AND JUPYTER
OVERVIEW
For this course, we will use WinPython, an easy-to-use Python distribution for Windows. WinPython comes
with Jupyter and a collection of useful scientific computing packages such as NumPy, SciPy and Matplotlib.
INSTRUCTIONS
Go to the WinPython webpage here to download the 64-bit version of WinPython 3.5.4.1 — see the pictures
below.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


14

2. Install WinPython by launching the .exe file you downloaded in the previous step. The installer will ask
you where to put the WinPython folder. As you can see in the picture below, I just put it on my Desktop so
that it's easy to find.

3. Once the installation is complete, open the WinPython folder. To launch Jupyter, open Jupyter
Notebook.exe in the WinPython folder.

A command prompt window titled "C:\Windows\system32\cmd.exe - winipython_notebook.bat" should


appear — just leave this open while you use Jupyter. In addition, your default browser should open with the
Jupyter file browser. See the picture below.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


15

If you accidentally close your browser, you can get back to the Jupyter file browser at http://localhost:8888/,
as long as the command prompt window that opened earlier is still open.
5. Going forward, put any Jupyter notebooks you want to use in the notebooks folder in the WinPython
folder:

2) NumPy Basics (np.array, np.arrange, np.linespace, np.zeros, np.ones, np.random.random, np.empty)


1. np.array

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


16

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example 1
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

Output:
[1 2 3 4 5]
<class 'numpy.ndarray'>
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:
Example 2
Use a tuple to create a NumPy array:
import numpy as np

arr = np.array((1, 2, 3, 4, 5))

print(arr)

Output:
[1 2 3 4 5]

Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example 3
Create a 0-D array with value 42
import numpy as np

arr = np.array(42)

print(arr)

Output:
42

1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.

These are the most common and basic arrays.


SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
17

Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

Output:
[1 2 3 4 5]

2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.


Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

Output:
[[1 2 3]
[4 5 6]]

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.

These are often used to represent a 3rd order tensor.


Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

Output:
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


18

Check Number of Dimensions?


NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the
array have.

Example
Check how many dimensions the arrays have:
import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

Output:
0
1
2
3
2. np.arrange

numpy.arange() function
The arange() function is used to get evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop]. For integer arguments the function is
equivalent to the Python built-in range function, but returns an ndarray rather than a list.
When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use
linspace for these cases.
Syntax:
numpy.arange([start, ]stop, [step, ]dtype=None)

NumPy.arange() method Example - 1:


import numpy as np
np.arange(5)
Output:
array([0, 1, 2, 3, 4])
>>> np.arange(5.0)
array([ 0., 1., 2., 3., 4.])
NumPy.arange() method Example - 2:
>>> import numpy as np
>>> np.arange(5,9)
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
19

Output:
array([5, 6, 7, 8])
>>> np.arange(5,9,3)
array([5, 8])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
NumPy.arange() method Example - 3:
import numpy as np
arr=np.arange(start=1,stop=10,step=1)
print(arr)
Output:
[1,2,3,4,5,6,7,8,9]
NumPy.arange() method Example - 4:
import numoy as np
arr=np.arange(1,10,2)
print(arr)
Output:
[1 3 5 7 9 ]
NumPy.arange() method Example - 5:
import numpy as np
arr=np.arange(5)
print(arr)
Output:
[0 1 2 3 4 ]
3. np.linespace

numpy.linspace() function
The linspace() function returns evenly spaced numbers over a specified interval [start, stop].
The endpoint of the interval can optionally be excluded.
Syntax:
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

Example-1: NumPy.linspace() method


>>> import numpy as np
>>> np.linspace(3.0, 4.0, num=7)
array([ 3. , 3.16666667, 3.33333333, 3.5 , 3.66666667,
3.83333333, 4. ])
>>> np.linspace(3.0,4.0, num=7, endpoint=False)
array([ 3. , 3.14285714, 3.28571429, 3.42857143, 3.57142857,
3.71428571, 3.85714286])
>>> np.linspace(3.0,4.0, num=7, retstep=True)
(array([ 3. , 3.16666667, 3.33333333, 3.5 , 3.66666667,
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
20

3.83333333, 4. ]), 0.16666666666666666)

Example-2: NumPy.linspace() method

>>> np.linspace(2.0, 3.0, num=5)


array([2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)

Example-3: NumPy.linspace() method

import numpy as geek

# restep set to True


print("B\n", geek.linspace(2.0, 3.0, num=5, retstep=True), "\n")

# To evaluate sin() in long range


x = geek.linspace(0, 2, 10)
print("A\n", geek.sin(x))

Output :
B
(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)

A
[ 0. 0.22039774 0.42995636 0.6183698 0.77637192 0.8961922
0.9719379 0.99988386 0.9786557 0.90929743]
4. np.zeros

zeros() function
The zeros() function is used to get a new array of given shape and type, filled with zeros.
Syntax:
numpy.zeros(a, dtype=None, order='K', subok=True)

Example 1: numpy.zeros() function


>>> import numpy as np
>>> a = (3,2)
>>> np.zeros(a)
Output:
array([[ 0., 0.],

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


21

[ 0., 0.],
[ 0., 0.]])
Example 2: numpy.zeros() function
>>> import numpy as np
>>> a = (3,2)
>>> np.zeros(a)
Output:
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
Examples

>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0])
>>> np.zeros((2, 1))
array([[ 0.],
[ 0.]])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
dtype=[('x', '<i4'), ('y', '<i4')])

5. np.ones

ones() function
The ones() function is used to get a new array of given shape and type, filled with ones.
Syntax:
numpy.ones(shape, dtype=None, order='C')
Example-1: numpy.ones()
>>> import numpy as np
>>> np.ones(7)
array([ 1., 1., 1., 1., 1., 1., 1.])
>>> np.ones((2, 1))
array([[ 1.],
[ 1.]])
>>> np.ones(7,)
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
22

array([ 1., 1., 1., 1., 1., 1., 1.])


>>> x = (2, 3)
>>> np.ones(x)
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
Example-2: numpy.ones() where data type is float
>>> import numpy as np
>>> np.ones((2,2)) #default datatype float
array([[ 1., 1.],
[ 1., 1.]])
>>> np.ones((2,2), dtype=int)
array([[1, 1],
[1, 1]])
Example-3: numpy.ones()

>>> np.ones(5)
array([1., 1., 1., 1., 1.])
>>> np.ones((5,), dtype=int)
array([1, 1, 1, 1, 1])
>>> np.ones((2, 1))
array([[1.],
[1.]])
>>> s = (2,2)
>>> np.ones(s)
array([[1., 1.],
[1., 1.]])

6. np.empty

empty() function
The empty() function is used to create a new array of given shape and type, without initializing entries.
Syntax:
numpy.empty(shape, dtype=float, order='C')
Examples

>>> np.empty([2, 2])


array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]]) #uninitialized

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


23

>>> np.empty([2, 2], dtype=int)


array([[-1073741821, -1067949133],
[ 496041986, 19249760]]) #uninitialized

Example: numpy.empty() function


>>> import numpy as np
>>> np.empty(2)
array([ 6.95033087e-310, 1.69970835e-316])
>>> np.empty(32)
array([ 6.95033087e-310, 1.65350412e-316, 6.95032869e-310,
6.95032869e-310, 6.95033051e-310, 6.95033014e-310,
6.95033165e-310, 6.95033167e-310, 6.95033163e-310,
6.95032955e-310, 6.95033162e-310, 6.95033166e-310,
6.95033160e-310, 6.95033163e-310, 6.95033162e-310,
6.95033167e-310, 6.95033167e-310, 6.95033167e-310,
6.95033167e-310, 6.95033158e-310, 6.95033160e-310,
6.95033164e-310, 6.95033162e-310, 6.95033051e-310,
6.95033161e-310, 6.95033051e-310, 6.95033013e-310,
6.95033166e-310, 6.95033161e-310, 2.97403466e+289,
7.55774284e+091, 1.31611495e+294])
>>> np.empty([2, 2])
array([[7.74860419e-304, 8.32155212e-317],
[0.00000000e+000, 0.00000000e+000]])
>>> np.empty([2, 3])
array([[ 6.95033087e-310, 1.68240973e-316, 6.95032825e-310],
[ 6.95032825e-310, 6.95032825e-310, 6.95032825e-310]])

Example: numpy.empty() where data-type for the array is int


>>>import numpy as np
>>> np.empty([2, 2], dtype=int)
array([[140144669465496, 16250304],
[140144685653488, 140144685468840]])
>>> np.empty([2, 2], dtype=float)
array([[2.37015306e-316, 7.37071328e-315],
[9.06655519e-317, 2.00753892e-317]])
7 np.random.random
Example 1
Generate a random integer from 0 to 100:
from numpy import random

x = random.randint(100)

print(x)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


24

Output:
45

Example 2
>>> np.random.random_sample()
0.47108547995356098

>>> type(np.random.random_sample())
<type 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])

Generate Random Float


The random module's rand() method returns a random float between 0 and 1.
Example
Generate a random float from 0 to 1:
from numpy import random

x = random.rand()

print(x)

Output:
0.3420593363265507

Generate Random Array


In NumPy we work with arrays, and you can use the two methods from the above examples to make
random arrays.

Integers
The randint() method takes a size parameter where you can specify the shape of an array.

Example
Generate a 1-D array containing 5 random integers from 0 to 100:
from numpy import random

x=random.randint(100, size=(5))

print(x)

Output:
[6 37 28 98 78]

Example
Generate a 2-D array with 3 rows, each row containing 5 random numbers:
from numpy import random

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


25

x = random.rand(3, 5)

print(x)

Output:
[[0.14252791 0.44691071 0.59274288 0.73873487 0.22082345]
[0.00484242 0.36294206 0.88507594 0.56948479 0.15075563]
[0.69195833 0.75111379 0.92780785 0.57986471 0.6203633 ]]

Example

Three-by-two array of random numbers from [-5, 0):

>>> 5 * np.random.random_sample((3, 2)) - 5


array([[-3.99149989, -0.52338984],
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])

3) Arrays ( array.shape, len(array), array.ndim, array.dtype, array.astype(type), type(array))


Create a NumPy ndarray Object
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))
output
[1 2 3 4 5]
<class 'numpy.ndarray'>
type(): This built-in Python function tells us the type of the object passed to it. Like in above code it shows
that arr is numpy.ndarray type.
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:
Example
Use a tuple to create a NumPy array:
import numpy as np

arr = np.array((1, 2, 3, 4, 5))

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


26

print(arr)
output
[1 2 3 4 5]

1. array.shape
Shape of an Array
The shape of an array is the number of elements in each dimension.
Get the Shape of an Array
NumPy arrays have an attribute called shape that returns a tuple with each index having the number of
corresponding elements.
Example 1
Print the shape of a 2-D array:
import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

print(arr.shape)
output
(2, 4)

Example 2
import numpy as np

a = np.array([1, 2, 3]) # Create a rank 1 array


print(type(a)) # Prints "<class 'numpy.ndarray'>"
print(a.shape) # Prints "(3,)"
print(a[0], a[1], a[2]) # Prints "1 2 3"
a[0] = 5 # Change an element of the array
print(a) # Prints "[5, 2, 3]"

b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array


print(b.shape) # Prints "(2, 3)"
print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"
output
<class 'numpy.ndarray'>
(3,)
123
[5 2 3]
(2, 3)
124
Numpy also provides many functions to create arrays:
import numpy as np

a = np.zeros((2,2)) # Create an array of all zeros

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


27

print(a) # Prints "[[ 0. 0.]


# [ 0. 0.]]"

b = np.ones((1,2)) # Create an array of all ones


print(b) # Prints "[[ 1. 1.]]"

c = np.full((2,2), 7) # Create a constant array


print(c) # Prints "[[ 7. 7.]
# [ 7. 7.]]"

d = np.eye(2) # Create a 2x2 identity matrix


print(d) # Prints "[[ 1. 0.]
# [ 0. 1.]]"

e = np.random.random((2,2)) # Create an array filled with random values


print(e) # Might print "[[ 0.91940167 0.08143941]
# [ 0.68744134 0.87236687]]"
Output
[[0. 0.]
[0. 0.]]
[[1. 1.]]
[[7 7]
[7 7]]
[[1. 0.]
[0. 1.]]
[[0.51812047 0.63875385]
[0.27115569 0.30803601]]

Example 2
# this resizes the ndarray
import numpy as np

a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2)
print a
The output is as follows −
[[1, 2]
[3, 4]
[5, 6]]
Example 3
NumPy also provides a reshape function to resize an array.

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print (b)
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
28

The output is as follows −


[[1, 2]
[3, 4]
[5, 6]]
2. ndarray.ndim
This array attribute returns the number of array dimensions.
Example 1

# an array of evenly spaced numbers


import numpy as np
a = np.array([[1,2,3,4],[1,2,3,4]])
print (a.dim)
The output is as follows −
2
Example2:
import numpy as np
a=np.array([[[1,2,3],[4,5,6],[7,8,9]]])
print(a.ndim)
output:
3
3. The Length of an Array
We can create an array using any of the above variants and use different functions to work with and
manipulate the data.
Python len() method enables us to find the total number of elements in the array/object. That is, it returns
the count of the elements in the array/object.
Syntax:

len( given_arr_name )

Syntax:
len(array)
Let us now understand the way to find out the length of an array in the above variants of Python array.
Use the len() method to return the length of an array (the number of elements in an array).

Example
Return the number of elements in the cars array:
x = len(cars)
Example1:
Code:
print("Program to demonstrate the len() method in Python")
print("\n")
arr1 = [2,'educba', 3, 4.5] print("The given array is as follow:")
print(arr1)
print("\n")
print("The length of the given array arr1 is: ")
print(len(arr1))

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


29

output:
Program to demonstrate the len() method in python
The given array is as follows:
[2, 'educba', 3, 4.5]

The length of the given array arr1 is:


4
Finding the Length of an Array
Length of an array is the number of elements that are actually present in an array. You can make use
of len() function to achieve this. The len() function returns an integer value that is equal to the number of
elements present in that array.
Example2:
import numpy as np
a=np.array([1,2,3,4,5,6,7])
b=len(a)
print(b)
output:
7
Example3:
import numpy as np
a=np.array([[1,2,3,4],[5,6,7,8]])
b=len(a)
print(b)
output:
2
array.dtype:
Example1:
import numpy as np
a=np.array([1,2,3,4])
print(a.dtype)
output:
int64
Example2:
import numpy as np
a=np.array([1.0,2.0,3.0])
print(a.dtype)
output:
float64
Example3:
import numpy as np
a=np.array([1.0+4.0j])
print(a.dtype)
oputput:
complex128
Example4:
import numpy as np
a=np.array(“ABCD”)
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
30

print(a.dtype)
output:
u4
Example 5:
import numpy as np
a=np.array([True,Flase])
print(a.dtype)
output:
bool

arrray.astype
Example1:
import numpy as np
a=np.array([1,1.2,1])
print(a.astype(int))
output:
[1 1 2]

Example2:
import numpy as np
a=np.array([1.2,1.2,2.5])
Print(a.astype(float))
Output:
[1.2 1.2 2.5]

Example3:
import numpy as np
a=np.array([1,2,3])
Print(a.astype(float))
Output:
[1. 2. 3.]

Example4:
import numpy as n p
a=np.array([1,0,2])
Print(a.astype(bool))
Output:
[True False True]

Type(array):
Example1:
import numpy as np
a=np.array([1,2,3,4])
Print(type(a))
Output:
<class ‘numpy’ ndarray’>

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


31

4) Array Manipulation (np.append, np.insert, np.resize, np.delete, np.concatenate, np.vstack, np.hstack)


1. np.append
numpy.append() in Python
The numpy.append() function is available in NumPy package. As the name suggests, append means adding
something. The numpy.append() function is used to add or append new values to an existing numpy array.
This function adds the new values at the end of the array.
The numpy append() function is used to merge two arrays. It returns a new array, and the original array
remains unchanged.
Syntax
numpy.append(arr, values, axis=None)
Example 1: np.append()
import numpy as np
a=np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
b=np.array([[11, 21, 31], [42, 52, 62], [73, 83, 93]])
c=np.append(a,b)
c
Output:
array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 11, 21, 31, 42, 52, 62, 73, 83,93])
Examples

>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])


array([1, 2, 3, ..., 7, 8, 9])
When axis is specified, values must have the correct shape.

>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)


array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
Traceback (most recent call last):
...
ValueError: all the input arrays must have same number of dimensions, but
the array at index 0 has 2 dimension(s) and the array at index 1 has 1
dimension(s)

Example-1: numpy.append()
>>> import numpy as np
>>> np.append ([0, 1, 2], [[3, 4, 5], [6, 7, 8]])
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
Example-2: numpy.append()
>>> import numpy as np
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
32

>>> np.append([[0, 1, 2], [3, 4, 5]],[[6, 7, 8]], axis=0)


array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
Example 3
import numpy as np

arr1 = np.array([[1, 2], [3, 4]])


arr2 = np.array([[10, 20], [30, 40]])

# no axis provided, array elements will be flattened


arr_flat = np.append(arr1, arr2)

print(arr_flat)

Output
[ 1 2 3 4 10 20 30 40]
2. np.insert
This function inserts values in the input array along the given axis and before the given index. If the
type of values is converted to be inserted, it is different from the input array. Insertion is not done in
place and the function returns a new array. Also, if the axis is not mentioned, the input array is
flattened.
The insert() function takes the following parameters −
numpy.insert(arr, obj, values, axis)

Note that for higher dimensional inserts obj=0 behaves very different from obj=[0] just like arr[:,0,:] =
values is different from arr[:,[0],:] = values.
Examples

>>> a = np.array([[1, 1], [2, 2], [3, 3]])


>>> a
array([[1, 1],
[2, 2],
[3, 3]])
>>> np.insert(a, 1, 5)
array([1, 5, 1, ..., 2, 3, 3])
>>> np.insert(a, 1, 5, axis=1)
array([[1, 5, 1],
[2, 5, 2],
[3, 5, 3]])
Example
import numpy as np

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


33

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

print 'First array:'


print a
print '\n'

print 'Axis parameter not passed. The input array is flattened before insertion.'
print np.insert(a,3,[11,12])
print '\n'
print 'Axis parameter passed. The values array is broadcast to match input array.'

print 'Broadcast along axis 0:'


print np.insert(a,1,[11],axis = 0)
print '\n'

print 'Broadcast along axis 1:'


print np.insert(a,1,11,axis = 1)
Output
First array:
[[1 2]
[3 4]
[5 6]]

Axis parameter not passed. The input array is flattened before insertion.
[ 1 2 3 11 12 4 5 6]

Axis parameter passed. The values array is broadcast to match input array.
Broadcast along axis 0:
[[ 1 2]
[11 11]
[ 3 4]
[ 5 6]]

Broadcast along axis 1:


[[ 1 11 2]
[ 3 11 4]
[ 5 11 6]]
3. np.resize
numpy.resize() function
The resize() function is used to create a new array with the specified shape.
If the new array is larger than the original array, then the new array is filled with repeated copies of a.
Syntax:
numpy.resize(a, new_shape)

Example-1: numpy.resize() function

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


34

>>> import numpy as np


>>> a = np.array([[1,2], [3,4]])
>>> np.resize(a, (3,2))
Output:
array([[1, 2],
[3, 4],
[1, 2]])
Example-2: numpy.resize() ffunction
>>> import numpy as np
>>> a = np.array([[1,2], [3,4]])
>>> np.resize(a, (2,3))
Output:
array([[1, 2, 3],
[4, 1, 2]])
Example-3: numpy.resize() ffunction
>>> import numpy as np
>>> a = np.array([[1,2], [3,4]])
>>> np.resize(a, (2,4))
Output:
array([[1, 2, 3, 4],
[1, 2, 3, 4]])

Examples

>>> a=np.array([[0,1],[2,3]])
>>> np.resize(a,(2,3))
array([[0, 1, 2],
[3, 0, 1]])
>>> np.resize(a,(1,4))
array([[0, 1, 2, 3]])
>>> np.resize(a,(2,4))
array([[0, 1, 2, 3],
[0, 1, 2, 3]])
Example
import numpy as np
a = np.array([[1,2,3],[4,5,6]])

print 'First array:'


print a
print '\n'

print 'The shape of first array:'


print a.shape

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


35

print '\n'
b = np.resize(a, (3,2))

print 'Second array:'


print b
print '\n'

print 'The shape of second array:'


print b.shape
print '\n'
# Observe that first row of a is repeated in b since size is bigger

print 'Resize the second array:'


b = np.resize(a,(3,3))
print b
The above program will produce the following output −
First array:
[[1 2 3]
[4 5 6]]

The shape of first array:


(2, 3)

Second array:
[[1 2]
[3 4]
[5 6]]

The shape of second array:


(3, 2)

Resize the second array:


[[1 2 3]
[4 5 6]
[1 2 3]]
Example 1:
In this example we can see that with the help of .resize() method, we have changed the shape of an array
from 1×6 to 2×3.
# importing the python module numpy
import numpy as np

# Making a random array


gfg = np.array([1, 2, 3, 4, 5, 6])

# Reshape the array permanently


gfg.resize(2, 3)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


36

print(gfg)

Output:
[[1 2 3]
[4 5 6]]
Example 2:
In this example we can see that, we are trying to resize the array of that shape which is type of out of
bound values. But numpy handles this situation to append the zeros when values are not existed in the
array.
# importing the python module numpy
import numpy as np

# Making a random array


gfg = np.array([1, 2, 3, 4, 5, 6])

# Required values 12, existing values 6


gfg.resize(3, 4)

print(gfg)

Output:
[[1 2 3 4]
[5 6 0 0]
[0 0 0 0]]

4. np.delete

numpy.delete() function
The delete() function returns a new array with sub-arrays along an axis deleted. For a one dimensional
array, this returns those entries not returned by arr[obj].
Syntax:
numpy.delete(arr, obj, axis=None)

Example-1: numpy.delete()
>>> import numpy as np
>>> arr = np.array([[0,1,2], [4,5,6], [7,8,9]])
>>> arr
Output:
array([[0, 1, 2],
[4, 5, 6],
[7, 8, 9]])
>>> np.delete(arr, 1, 0)
Output:

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


37

array([[0, 1, 2],
[7, 8, 9]])
Example-2: numpy.delete()
>>> import numpy as np
>>> np.delete(arr, np.s_[::2], 1)
Output:
array([[1],
[5],
[8]])
>>> np.delete(arr, [1, 2, 5], None)
Output:
array([0, 4, 5, 7, 8, 9])
Examples

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


>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1, 2, 3, 4],
[ 9, 10, 11, 12]])

np.delete(arr, np.s_[::2], 1)
array([[ 2, 4],
[ 6, 8],
[10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])

Code 1 : Deletion from 1D array


# Python Program illustrating
# numpy.delete()

import numpy as geek

#Working on 1D
arr = geek.arange(5)
print("arr : \n", arr)
print("Shape : ", arr.shape)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


38

# deletion from 1D array

object = 2
a = geek.delete(arr, object)
print("\ndeleteing {} from array : \n {}".format(object,a))
print("Shape : ", a.shape)

object = [1, 2]
b = geek.delete(arr, object)
print("\ndeleteing {} from array : \n {}".format(object,a))
print("Shape : ", a.shape)

Output : 

arr :
[0 1 2 3 4]
Shape : (5,)

deleteing arr 2 times :


[0 1 3 4]
Shape : (4,)

deleteing arr 3 times :


[0 3 4]
Shape : (4,)
5. np.concatenate

numpy.concatenate() function
The concatenate() function returns an ndarray of the provided type that satisfies requirements.
Syntax:
numpy.concatenate((a1, a2, ...), axis=0, out=None)

Example-1: numpy.concatenate()
>>> import numpy as np
>>> x = np.array([[3, 4], [5, 6]])
>>> y = np.array([[7, 8]])
>>> np.concatenate((x,y), axis=0)
Output:
array([[3, 4],
[5, 6],
[7, 8]])
Example-2: numpy.concatenate()
>>> import numpy as np
>>> x = np.array([[3, 4], [5, 6]])
>>> y = np.array([[7, 8]])
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
39

>>> np.concatenate((x, y.T), axis=1)


Output:
array([[3, 4, 7],
[5, 6, 8]])
Example-3: numpy.concatenate()
>>> import numpy as w3r
>>> x = w3r.array([[3, 4], [5, 6]])
>>> y = w3r.array([[7, 8]])
>>> w3r.concatenate((x, y), axis=None)
Output:
array([3, 4, 5, 6, 7, 8])
Example-4: numpy.concatenate()
>>> import numpy as w3r
>>> x = w3r.ma.arange(5)
>>> x[1] = w3r.ma.masked
>>> y = w3r.arange(3, 7)
>>> x
Output:
masked_array(data = [0 -- 2 3 4],
mask = [False True False False False],
fill_value = 999999)

>>> y
Output:
array([3, 4, 5, 6])
>>> w3r.concatenate([x, y])
Output:
masked_array(data = [0 1 2 3 4 3 4 5 6],
mask = False,
fill_value = 999999)

>>> w3r.ma.concatenate([x, y])


Output:
masked_array(data = [0 -- 2 3 4 3 4 5 6],
mask = [False True False False False False False False False],
fill_value = 999999)
Example-5: numpy.concatenate()

import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
np.concatenate((a, b), axis=0)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


40

Output:
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
Output:
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
Output:
array([1, 2, 3, 4, 5, 6])

6. np.vstack

numpy.vstack() function
The vstack() function is used to stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped
to (1,N).
This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a
height (first axis), width (second axis), and r/g/b channels (third axis). T
Syntax:
numpy.vstack(tup)

Example-1: numpy.vstack() function


>>> import numpy as np
>>> x = np.array([3, 5, 7])
>>> y = np.array([5, 7, 9])
>>> np.vstack((x,y))
Output:
array([[3, 5, 7],
[5, 7, 9]])
Example-2: numpy.vstack() function
>>> import numpy as np
>>> x = np.array([[3], [5], [7]])
>>> y = np.array([[5], [7], [9]])
>>> np.vstack((x,y))
Output:
array([[3],
[5],

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


41

[7],
[5],
[7],
[9]])
Example 3

>>> a = np.array([1, 2, 3])


>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
Example 4

a = np.array([[1], [2], [3]])


>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[4],
[5],
[6]])

7. np.hstack

numpy.hstack() function
The hstack() function is used to stack arrays in sequence horizontally (column wise).
This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates
along the first axis. Rebuilds arrays divided by hsplit.
This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a
height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack
and block provide more general stacking and concatenation operations.
Syntax:
numpy.hstack(tup)

Example-1: numpy.hstack()
>>> import numpy as np
>>> x = np.array((3,5,7))
>>> y = np.array((5,7,9))

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


42

>>> np.hstack((x,y))
Output:
array([3, 5, 7, 5, 7, 9])
Example-2: numpy.hstack()
>>> import numpy as np
>>> x = np.array([[3], [5], [7]])
>>> y = np.array([[5], [7], [9]])
>>> np.hstack((x,y))
Output:
array([[3, 5],
[5, 7],
[7, 9]])
Example-3: numpy.hstack()
import numpy as np
a = np.array((1,2,3))
b = np.array((4,5,6))
np.hstack((a,b))
Output:
array([1, 2, 3, 4, 5, 6])
import numpy as np
a = np.array([[1],[2],[3]])
b = np.array([[4],[5],[6]])
np.hstack((a,b))
Output:
array([[1, 4],
[2, 5],
[3, 6]])

8. np.dstack

numpy.dstack() function
The dstack() is used to stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped
to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1). Rebuilds arrays divided by dsplit.
This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a
height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and
block provide more general stacking and concatenation operations.
Syntax:
numpy.dstack(tup)

Example-1: numpy.dstack()
>>> import numpy as np
>>> x = np.array((3, 5, 7))

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


43

>>> y = np.array((5, 7, 9))


>>> np.dstack((x,y))
Output:
array([[[3, 5],
[5, 7],
[7, 9]]])
Example-2: numpy.dstack()
>>> import numpy as np
>>> x = np.array([[3], [5], [7]])
>>> y = np.array([[5], [7], [9]])
>>> np.dstack((x,y))
Output:
array([[[3, 5]],

[[5, 7]],

[[7, 9]]])

5) Mathematical Operations ( np.add, np.substract, np.divide, np.multiply, np.sqrt, np.sin, np.cos, np.log,
np.dot, np.roots) , Statistical Operations( np.mean, np.median, np.std, array.corrcoef( ) )
Arithmetic operations are possible only if the array has the same structure and dimensions. We carry out the
operations following the rules of array manipulation. We have both functions and operators to perform these
functions.
1. np.add
NumPy Add function
This function is used to add two arrays. If we add arrays having dissimilar shapes we get “Value Error”.

import numpy as np
a = np.array([10,20,100,200,500])
b = np.array([3,4,5,6,7])
np.add(a, b)

Output
array([ 13, 24, 105, 206, 507])
NumPy Add Operator
We can also use the add operator “+” to perform addition of two arrays.

import numpy as np
a = np.array([10,20,100,200,500])
b = np.array([3,4,5,6,7])
print(a+b)

Output
[ 13 24 105 206 507]
2. np.substract

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


44

NumPy Subtract function


We use this function to output the difference of two arrays. If we subtract two arrays having dissimilar
shapes we get “Value Error”.

import numpy as np
a = np.array([10,20,100,200,500])
b = np.array([3,4,5,6,7])
np.subtract(a, b)

Output
array([ 7, 16, 95, 194, 493])
NumPy Subtract Operator
We can also use the subtract operator “-” to produce the difference of two arrays.

import numpy as np
a = np.array([10,20,100,200,500])
b = np.array([3,4,5,6,7])
print(a-b)

Output
[ 7 16 95 194 493]

3. np.multiply
NumPy Multiply function
We use this function to output the multiplication of two arrays. We cannot work with dissimilar arrays.

import numpy as np
a = np.array([7,3,4,5,1])
b = np.array([3,4,5,6,7])
np.multiply(a, b)

Output

array([21, 12, 20, 30, 7])


NumPy Multiply Operator
We can also use the multiplication operator “*” to get the product of two arrays.

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

Output
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
45

[21 12 20 30 7]
4. np.divide
NumPy Divide Function
We use this function to output the division of two arrays. We cannot divide dissimilar arrays.

import numpy as np
a = np.array([7,3,4,5,1])
b = np.array([3,4,5,6,7])
np.divide(a,b)

Output
array([2.33333333, 0.75 , 0.8 , 0.83333333, 0.14285714])
NumPy Divide Operator
We can also use the divide operator “/” to divide two arrays.

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

Output
[2.33333333 0.75 0.8 0.83333333 0.14285714]
NumPy Mod and Remainder function
We use both the functions to output the remainder of the division of two arrays.
NumPy Remainder Function

import numpy as np
a = np.array([7,3,4,5,1])
b = np.array([3,4,5,6,7])
np.remainder(a,b)

Output
array([1, 3, 4, 5, 1])
NumPy Mod Function

import numpy as np
a = np.array([7,3,4,5,1])
b = np.array([3,4,5,6,7])
np.mod(a,b)

Output
array([1, 3, 4, 5, 1])

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


46

NumPy Power Function


This Function treats the first array as base and raises it to the power of the elements of the second array.

import numpy as np
a = np.array([7,3,4,5,1])
b = np.array([3,4,5,6,7])
np.power(a,b)

Output
array([ 343, 81, 1024, 15625, 1])
5. np.sqrt
sqrt has–consistent with common convention–as its branch cut the real “interval” [-inf, 0), and is continuous
from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be
continuous.
Examples

>>> np.sqrt([1,4,9])
array([ 1., 2., 3.])
>>> np.sqrt([4, -1, -3+4J])
array([ 2.+0.j, 0.+1.j, 1.+2.j])
>>> np.sqrt([4, -1, np.inf])
array([ 2., nan, inf])

Example 1
import numpy as np

arr = [1, 9, 25, 49]

arr_sqrt = np.sqrt(arr)

print(arr_sqrt)
Output:
[1. 3. 5. 7.]
Example Codes: numpy.sqrt() With out Parameter
import numpy as np

arr = [1, 9, 25, 49]


out_arr = np.zeros(4)

arr_sqrt = np.sqrt(arr, out_arr)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


47

print(out_arr)
print(arr_sqrt)
Output:
[1. 3. 5. 7.]
[1. 3. 5. 7.]
Example Codes: numpy.sqrt() With Complex Numbers
import numpy as np

arr = [3+4j, -5+12j, 8-6j, -15-8j]

arr_sqrt = np.sqrt(arr)

print(arr_sqrt)
Output:
[2.+1.j 2.+3.j 3.-1.j 1.-4.j]
6. np.sin
Trigonometric Functions
NumPy provides the ufuncs sin(), cos() and tan() that take values in radians and produce the corresponding
sin, cos and tan values.
Example 1
Find sine value of PI/2:
import numpy as np

x = np.sin(np.pi/2)

print(x)

Output
1.0
Example 2
Find sine values for all of the values in arr:
import numpy as np

arr = np.array([np.pi/2, np.pi/3, np.pi/4, np.pi/5])

x = np.sin(arr)

print(x)

Output

[1. 0.8660254 0.70710678 0.58778525]


SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
48

Example 3
import numpy as np
np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
array([ 0. , 0.5 , 0.70710678, 0.8660254, 1. ])

Example 4

import numpy as np
a = np.array([0,30,45,60,90])

print 'Sine of different angles:'


# Convert to radians by multiplying with pi/180
print np.sin(a*np.pi/180)
print '\n'
7. np.cos
Example 1

np.cos(np.array([0, np.pi/2, np.pi]))


output
array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00])

Example 2
import numpy as np
print("sine: array of angles given in degrees")
print(np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
print("cosine: array of angles given in degrees")
print(np.cos(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
print("tangent: array of angles given in degrees")
print(np.tan(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
Sample Output:
sine: array of angles given in degrees
[ 0. 0.5 0.70710678 0.8660254 1. ]
cosine: array of angles given in degrees
[ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
tangent: array of angles given in degrees
[ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]

Example 3
import numpy as np
import math

in_array = [0, math.pi / 2, np.pi / 3, np.pi]

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


49

print ("Input array : \n", in_array)

cos_Values = np.cos(in_array)
print ("\nCosine values : \n", cos_Values)

Output:
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
Cosine values :
[ 1.00000000e+00 6.12323400e-17 5.00000000e-01 -1.00000000e+00]
Example 4
import numpy as np
a = np.array([0,30,45,60,90])

print 'Sine of different angles:'


# Convert to radians by multiplying with pi/180
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'
Output
Sine of different angles:
[ 0. 0.5 0.70710678 0.8660254 1. ]

Cosine values for angles in array:


[ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]

Example to cover all the functions


import numpy as np
a = np.array([0,30,45,60,90])

print 'Array containing sine values:'


sin = np.sin(a*np.pi/180)
print sin
print '\n'

print 'Compute sine inverse of angles. Returned values are in radians.'


inv = np.arcsin(sin)
print inv
print '\n'

print 'Check result by converting to degrees:'

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


50

print np.degrees(inv)
print '\n'

print 'arccos and arctan functions behave similarly:'


cos = np.cos(a*np.pi/180)
print cos
print '\n'

print 'Inverse of cos:'


inv = np.arccos(cos)
print inv
print '\n'

print 'In degrees:'


print np.degrees(inv)
print '\n'

print 'Tan function:'


tan = np.tan(a*np.pi/180)
print tan
print '\n'

print 'Inverse of tan:'


inv = np.arctan(tan)
print inv
print '\n'

print 'In degrees:'


print np.degrees(inv)
Its output is as follows −
Array containing sine values:
[ 0. 0.5 0.70710678 0.8660254 1. ]

Compute sine inverse of angles. Returned values are in radians.


[ 0. 0.52359878 0.78539816 1.04719755 1.57079633]

Check result by converting to degrees:


[ 0. 30. 45. 60. 90.]

arccos and arctan functions behave similarly:


[ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]

Inverse of cos:
[ 0. 0.52359878 0.78539816 1.04719755 1.57079633]

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


51

In degrees:
[ 0. 30. 45. 60. 90.]

Tan function:
[ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]

Inverse of tan:
[ 0. 0.52359878 0.78539816 1.04719755 1.57079633]

In degrees:
[ 0. 30. 45. 60. 90.]

8. np,log
Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = x. The
convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log always returns real output. For each value that cannot be expressed
as a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log is a complex analytical function that has a branch cut [-inf, 0] and is
continuous from above on it. log handles the floating-point negative zero as an infinitesimal negative
number, conforming to the C99 standard.
Examples

>>> np.log([1, np.e, np.e**2, 0])


Output

array([ 0., 1., 2., -Inf])


Example 1
import numpy as np

arr = np.arange(1, 10)

print(np.log(arr))
Output
[0. 0.69314718 1.09861229 1.38629436 1.60943791 1.79175947
1.94591015 2.07944154 2.19722458]
Example 2

import numpy as np

in_array = [1, 3, 5, 2**8]


print ("Input array : ", in_array)

out_array = np.log(in_array)
print ("Output array : ", out_array)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


52

print("\nnp.log(4**4) : ", np.log(4**4))


print("np.log(2**8) : ", np.log(2**8))

Output :
Input array : [1, 3, 5, 256]
Output array : [ 0. 1.09861229 1.60943791 5.54517744]

np.log(4**4) : 5.54517744448
np.log(2**8) : 5.54517744448
Log at Base 2
Use the log2() function to perform log at the base 2.
Example
Find log at base 2 of all elements of following array:
import numpy as np

arr = np.arange(1, 10)

print(np.log2(arr))

Output
[0. 1. 1.5849625 2. 2.32192809 2.5849625
2.80735492 3. 3.169925 ]
Log at Base 10
Use the log10() function to perform log at the base 10.
Example
Find log at base 10 of all elements of following array:
import numpy as np

arr = np.arange(1, 10)

print(np.log10(arr))
Output
[0. 0.30103 0.47712125 0.60205999 0.69897 0.77815125
0.84509804 0.90308999 0.95424251]
Log at Any Base
NumPy does not provide any function to take log at any base, so we can use the frompyfunc() function
along with inbuilt function math.log() with two input parameters and one output parameter:
Example
from math import log
import numpy as np

nplog = np.frompyfunc(log, 2, 1)

print(nplog(100, 15))
Output
1.7005483074552052
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
53

Example
import numpy as np
a=np.array([2, 4, 6, 3**8])
a
b=np.log(a)
b
c=np.log2(a)
c
d=np.log10(a)
d

output
array([ 2, 4, 6, 6561])
array([0.69314718, 1.38629436, 1.79175947, 8.78889831])
array([ 1. , 2. , 2.5849625 , 12.67970001])
array([0.30103 , 0.60205999, 0.77815125, 3.81697004])
9. np.dot
numpy.dot(a, b, out=None)
Dot product of two arrays. Specifically,
 If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
 If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is
preferred.
 If either a or b is 0-D (scalar), it is equivalent to multiply and
using numpy.multiply(a, b) or a * b is preferred.
 If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
 If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last
axis of a and the second-to-last axis of b:

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])


Examples

>>> np.dot(3, 4)
Output
12
Neither argument is complex-conjugated:

>>> np.dot([2j, 3j], [2j, 3j])


(-13+0j)
For 2-D arrays it is the matrix product:

>>> a = [[1, 0], [0, 1]]

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


54

>>> b = [[4, 1], [2, 2]]


>>> np.dot(a, b)
array([[4, 1],
[2, 2]])

a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
>>> sum(a[2,3,2,:] * b[1,2,:,2])
499128

Example
import numpy.matlib
import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
np.dot(a,b)
It will produce the following output −
[[37 40]
[85 92]]
Note that the dot product is calculated as −
[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]

Example 1:
import numpy as np
a=np.dot(6,12)
a
Output:
72
Example 2:
import numpy as np
a=np.dot([2j, 3j], [5j, 8j])
a
Output:
(-34+0j)

Example 3:
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
55

import numpy as np
a = [[1, 2], [4, 1]]
b = [[4, 11], [2, 3]]
c=np.dot(a, b)
c
Output:

array([[ 8, 17],
[18, 47]])
Example 4:
import numpy as np
x = np.arange(3*4*5*6).reshape((3,4,5,6))
y = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
p=np.dot(a, b)[2,3,2,1,2,2]
q=sum(a[2,3,2,:] * b[1,2,:,2])
p
q
Output:
499128
499128

10. np.roots
Example 1

11. >>> coeff = [3.2, 2, 1]


12. >>> np.roots(coeff)
13. array([-0.3125+0.46351241j, -0.3125-0.46351241j])
Example 2
# importing numpy as geek
import numpy as geek

p = [1, 2, 3]

gfg = geek.roots(p)

print (gfg)

Output :
[-1.+1.41421356j -1.-1.41421356j]
Example 3
# importing numpy as geek

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


56

import numpy as geek

p = [3.2, 2, 1]

gfg = geek.roots(p)

print (gfg)

Output :
[-0.3125+0.46351241j -0.3125-0.46351241j]

Statistical Operations ( np.mean, np.median, np.std, array.corrcoef( )


Finding maximum and minimum of array in NumPy
NumPy np.amin()and np.amax()functions are useful to determine the minimum and maximum value of
array elements along a specified axis.

import numpy as np
arr= np.array([[1,23,78],[98,60,75],[79,25,48]])
print(arr)
#Minimum Function
print(np.amin(arr))
#Maximum Function
print(np.amax(arr))

Output
[[ 1 23 78]
[98 60 75]
[79 25 48]]
1
98

1. np.mean
np.mean()- It determines the mean value of the data set.
Mean is the sum of the elements divided by its sum and given by the following formula:
It calculates the mean by adding all the items of the arrays and then divides it by the number of elements. We
can also mention the axis along which the mean can be calculated.

import numpy as np
a = np.array([5,6,7])
print(a)
print(np.mean(a))

Output

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


57

[5 6 7]
6.0
Example 1

>>> a = np.array([[1, 2], [3, 4]])


>>> np.mean(a)
2.5
>>> np.mean(a, axis=0)
array([2., 3.])
>>> np.mean(a, axis=1)
array([1.5, 3.5])
Example 2

# Python Program illustrating


# numpy.mean() method
import numpy as np

# 1D array
arr = [20, 2, 7, 1, 34]

print("arr : ", arr)


print("mean of arr : ", np.mean(arr))

Output :
arr : [20, 2, 7, 1, 34]
mean of arr : 12.8
Example 3

# Python Program illustrating


# numpy.mean() method
import numpy as np

# 2D array
arr = [[14, 17, 12, 33, 44],
[15, 6, 27, 8, 19],
[23, 2, 54, 1, 4, ]]

# mean of the flattened array


print("\nmean of arr, axis = None : ", np.mean(arr))

# mean along the axis = 0


print("\nmean of arr, axis = 0 : ", np.mean(arr, axis = 0))

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


58

# mean along the axis = 1


print("\nmean of arr, axis = 1 : ", np.mean(arr, axis = 1))

out_arr = np.arange(3)
print("\nout_arr : ", out_arr)
print("mean of arr, axis = 1 : ",
np.mean(arr, axis = 1, out = out_arr))

Output :
mean of arr, axis = None : 18.6
mean of arr, axis = 0 : [17.33333333 8.33333333 31. 14. 22.33333333]
mean of arr, axis = 1 : [24. 15. 16.8]
out_arr : [0 1 2]
mean of arr, axis = 1 : [24 15 16]
Example 4:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b=np.mean(a)
b
x = np.array([[5, 6], [7, 34]])
y=np.mean(x)
y
Output:
2.5
13.0

2. np.median
Median is the middle element of the array. The formula differs for odd and even sets.
It can calculate the median for both one-dimensional and multi-dimensional arrays. Median separates the higher
and lower range of data values.

import numpy as np
a = np.array([5,6,7])
print(a)
print(np.median(a))

Output
[5 6 7]
6.0
Example 1:
# numpy.median() method

import numpy as np

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


59

# 1D array
arr = [20, 2, 7, 1, 34]

print("arr : ", arr)


print("median of arr : ", np.median(arr))

Output :
arr : [20, 2, 7, 1, 34]
median of arr : 7.0
Example 2:

# Python Program illustrating


# numpy.median() method
import numpy as np

# 2D array
arr = [[14, 17, 12, 33, 44],
[15, 6, 27, 8, 19],
[23, 2, 54, 1, 4, ]]

# median of the flattened array


print("\nmedian of arr, axis = None : ", np.median(arr))

# median along the axis = 0


print("\nmedian of arr, axis = 0 : ", np.median(arr, axis = 0))

# median along the axis = 1


print("\nmedian of arr, axis = 1 : ", np.median(arr, axis = 1))

out_arr = np.arange(3)
print("\nout_arr : ", out_arr)
print("median of arr, axis = 1 : ",
np.median(arr, axis = 1, out = out_arr))

Output :
median of arr, axis = None : 15.0

median of arr, axis = 0 : [15. 6. 27. 8. 19.]

median of arr, axis = 1 : [17. 15. 4.]

out_arr : [0 1 2]
median of arr, axis = 1 : [17 15 4]

Example 3:

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


60

import numpy as ppool


a=ppool.array([10,12,14,16,20])
print(ppool.median(a))

b=ppool.array([12,13,16,18,19,22])
print(ppool.median(b))
Output:
14.0
17.0

Example 4: NumPy Median with axis=0


import numpy as np
a=[
[1,2,3,4,5],
[6,7,8,9,10],
[0,5,7,8,9],
[11,4,6,45,1]]
print(np.median(a,axis=0))
Output:
[3.5 4.5 6.5 8.5 7. ]

Examples

>>> a = np.array([[10, 7, 4], [3, 2, 1]])


>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> np.median(a)
3.5
>>> np.median(a, axis=0)
array([6.5, 4.5, 2.5])
>>> np.median(a, axis=1)
array([7., 2.])
>>> m = np.median(a, axis=0)
>>> out = np.zeros_like(m)
>>> np.median(a, axis=0, out=m)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
>>> b = a.copy()

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


61

>>> np.median(b, axis=1, overwrite_input=True)


array([7., 2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.median(b, axis=None, overwrite_input=True)
3.5
>>> assert not np.all(a==b)

3. np.std
Standard Deviation
Standard deviation is the square root of the average of square deviations from mean. The formula for
standard deviation is:

import numpy as np
a = np.array([5,6,7])
print(a)
print(np.std(a))

Output
[5 6 7]
0.816496580927726
Examples

>>> a = np.array([[1, 2], [3, 4]])


>>> np.std(a)
1.1180339887498949 # may vary
>>> np.std(a, axis=0)
array([1., 1.])
>>> np.std(a, axis=1)
array([0.5, 0.5])

In single precision, std() can be inaccurate:

>>> a = np.zeros((2, 512*512), dtype=np.float32)


>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.std(a)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


62

0.45000005

Computing the standard deviation in float64 is more accurate:

>>> np.std(a, dtype=np.float64)


0.44999999925494177 # may vary

Specifying a where argument:

>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> np.std(a)
2.614064523559687 # may vary
>>> np.std(a, where=[[True], [True], [False]])
2.0

Example :
a=np.array([[1,4,7,10],[2,5,8,11]])
b=np.std(a)
b
Output:
3.391164991562634

4. array.corrcoef
Examples
In this example we generate two random arrays, xarr and yarr, and compute the row-wise and column-
wise Pearson correlation coefficients, R. Since rowvar is true by default, we first find the row-wise
Pearson correlation coefficients between the variables of xarr.

>>> import numpy as np


>>> rng = np.random.default_rng(seed=42)
>>> xarr = rng.random((3, 3))
>>> xarr
array([[0.77395605, 0.43887844, 0.85859792],
[0.69736803, 0.09417735, 0.97562235],
[0.7611397 , 0.78606431, 0.12811363]])
>>> R1 = np.corrcoef(xarr)
>>> R1
array([[ 1. , 0.99256089, -0.68080986],

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


63

[ 0.99256089, 1. , -0.76492172],
[-0.68080986, -0.76492172, 1. ]])

6) NumPy Data types


Type Type Code
0 int8 i1
1 uint8 u1
2 int16 i2
3 uint16 u2
4 int or int32 i4 or i
5 uint32 u4
6 int64 i8
7 uint64 u8
8 float16 f2
9 float32 f4 or f
10 float or float64 f8 or d
11 float128 f16 or g
12 complex64 c8
complex or
13 c16
complex128
14 bool None
15 object O
16 string_ S
17 unicode_ U

In [1]:
import numpy as np
import pandas as pd
Numpy Data Types
Numpy has the following data types:
 int
 float
 complex
 bool

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


64

 string
 unicode
 object
The numeric data types have various precisions like 32-bit or 64-bit.
Numpy data types can be represented using either Type or Type Code
In [2]:
dtypes = pd.DataFrame(
{
'Type': [
'int8',
'uint8',
'int16',
'uint16',
'int or int32',
'uint32',
'int64',
'uint64',
'float16',
'float32',
'float or float64',
'float128',
'complex64',
'complex or complex128',
'bool',
'object',
'string_',
'unicode_',
],

'Type Code': [
'i1',
'u1',
'i2',
'u2',
'i4 or i',
'u4',
'i8',
'u8',
'f2',
'f4 or f',
'f8 or d',
'f16 or g',
'c8',
'c16',

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


65

None,
'O',
'S',
'U',
]
}
)

dtypes
Out[2]:
Data types can be defined at creating the numpy array and converted to other types later.
You can use either type, type code or np dot methods to define the data type of an array, but when you
use np dot method to define the data type, it can only follow type rather than type code.
In [3]:
arr = np.array([1,2,3], dtype='f4')
arr.dtype
Out[3]:
dtype('float32')
In [4]:
# Identical to the above
arr = np.array([1,2,3], dtype='float32')
arr.dtype
Out[4]:
dtype('float32')
In [5]:
arr = np.array([1+2j, 3-4j], dtype=np.complex64)
arr.dtype
Out[5]:
dtype('complex64')
In [6]:
# Identical to the above
arr = np.array([1+2j, 3-4j], dtype='c8')
arr.dtype
Out[6]:
dtype('complex64')
In [7]:
# ERROR
arr = np.array([1+2j, 3-4j], dtype=np.c8)
arr.dtype
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-a5f30f9069f2> in <module>()
1 # ERROR
----> 2 arr = np.array([1+2j, 3-4j], dtype=np.c8)
3 arr.dtype
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
66

AttributeError: module 'numpy' has no attribute 'c8'


Type Conversion
astype method: convert the data type of an array to other data types.
Notice that astype returns a copy of the array instead of converting the data type in place. You need to
assign the copy to the original array or a new array.
In [8]:
arr = np.array([1,2,3], dtype='int16')
print('Original Data Type: ' + str(arr.dtype))

arr = arr.astype(np.float32)
print('Data Type After Conversion: ' + str(arr.dtype))
Original Data Type: int16
Data Type After Conversion: float32
WARNING: be cautious about data overflow when you downcast the data type (from higher precision to
lower precision). Some unexpected and undefined values might occur and it is usually difficult to debug
such issues.
In [9]:
# An example of integer overflow at downcasting
arr = np.array([126,127,256], dtype='int16')
print('np array before type conversion: ' + str(arr))

# Range of int8 [-128, 127], 256 overflows after conversion


arr = arr.astype('int8')
print('np array after type conversion: ' + str(arr))
np array before type conversion: [126 127 256]
np array after type conversion: [126 127 0]
String and Unicode Data Type
The string_ and unicode_ data types are all implicitly fixed-length.
The length of the string is given by their type code appended with a number. For example, S3 represents
string of length 3; U10 represents unicode of length 10. Otherwise, the default length is the length of the
longest string in the array.
If the length of a string in the array is shorter than the length of the data type defined or converted to, the
string will be truncated.
In [10]:
# An example of truncated string
s = np.array(['abc', 'defg'], dtype='S3')
print(s)

# An example of truncated unicode


s = np.array(['abcd', 'efghi'], dtype='U3')
print(s)
[b'abc' b'def']
['abc' 'efg']
In [11]:

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


67

arr = np.array(['a', 'ab', 'abc'], dtype=np.string_)


print('The array is ' + str(arr))
print('The data type is ' + str(arr.dtype) + ' because the longest string in the array is "abc" and its length is
3.')

arr = np.array(['a', 'abc', 'abcd'], dtype=np.unicode_)


print('The array is ' + str(arr))
print('The data type is ' + str(arr.dtype) + ' because the longest unicode in the array is "abcd" and its length is
4.')
The array is [b'a' b'ab' b'abc']
The data type is |S3 because the longest string in the array is "abc" and its length is 3.
The array is ['a' 'abc' 'abcd']
The data type is <U4 because the longest unicode in the array is "abcd" and its length is 4.
What do "|" and "<" in the data types above mean?
They are the byte order indicators, which are beyond the scope of this tutorial.
Further readings if you are interested:
 https://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.byteorder.html
 https://en.wikipedia.org/wiki/Endianness

7) NumPy ndarray
The most important object defined in NumPy is an N-dimensional array type called ndarray. It describes
the collection of items of the same type. Items in the collection can be accessed using a zero-based index.
Every item in an ndarray takes the same size of block in the memory. Each element in ndarray is an object
of data-type object (called dtype).
Any item extracted from ndarray object (by slicing) is represented by a Python object of one of array scalar
types. The following diagram shows a relationship between ndarray, data type object (dtype) and array
scalar type –

An instance of ndarray class can be constructed by different array creation routines described later in the
tutorial. The basic ndarray is created using an array function in NumPy as follows −
numpy.array
It creates an ndarray from any object exposing array interface, or from any method that returns an array.
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
The above constructor takes the following parameters −
Sr.No Parameter & Description
.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


68

1 object
Any object exposing the array interface method returns an array, or any (nested) sequence.

2 dtype
Desired data type of array, optional

3 copy
Optional. By default (true), the object is copied

4 order
C (row major) or F (column major) or A (any) (default)

5 subok
By default, returned array forced to be a base class array. If true, sub-classes passed
through

6 ndmin
Specifies minimum dimensions of resultant array
Take a look at the following examples to understand better.

Example 1
import numpy as np
a = np.array([1,2,3])
print a
The output is as follows −
[1, 2, 3]

Example 2
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print a
The output is as follows −
[[1, 2]
[3, 4]]
Example 3
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print a
The output is as follows −
[[1, 2, 3, 4, 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


69

print a
The output is as follows −
[ 1.+0.j, 2.+0.j, 3.+0.j]

The ndarray object consists of contiguous one-dimensional segment of computer memory, combined with


an indexing scheme that maps each item to a location in the memory block. The memory block holds the
elements in a row-major order (C style) or a column-major order (FORTRAN or MatLab style).

(Another material)
7) NumPy ndarray
Create a NumPy ndarray Object
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

output
[1 2 3 4 5]
<class 'numpy.ndarray'>
type(): This built-in Python function tells us the type of the object passed to it. Like in above code it shows
that arr is numpy.ndarray type.

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:
Example
Use a tuple to create a NumPy array:
import numpy as np

arr = np.array((1, 2, 3, 4, 5))

print(arr)

output
[1 2 3 4 5]

Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
nested array: are arrays that have arrays as their elements.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


70

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
Create a 0-D array with value 42
import numpy as np

arr = np.array(42)

print(arr)
output
42
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)
output
[1 2 3 4 5]
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations called numpy.mat
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

output
[[1 2 3]
[4 5 6]]
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


71

print(arr)

output
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]
Check Number of Dimensions?
NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the
array have.
Example
Check how many dimensions the arrays have:
import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

output
0
1
2
3
Higher Dimensional Arrays
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using the ndmin argument.
Example
Create an array with 5 dimensions and verify that it has 5 dimensions:
import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('number of dimensions :', arr.ndim)
output
[[[[[1 2 3 4]]]]]
number of dimensions : 5

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


72

In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the vector,
the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is 3D array and
1st dim has 1 element that is a 4D array.

8) NumPy String Operations


Numpy | String Operations
 Last Updated : 19 Apr, 2020
This module is used to perform vectorized string operations for arrays of dtype numpy.string_ or
numpy.unicode_. All of them are based on the standard string functions in Python’s built-in library.
String Operations –
numpy.lower() : This function returns the lowercase string from the given string. It converts all uppercase
characters to lowercase. If no uppercase characters exist, it returns the original string.

# Python program explaining


# numpy.lower() function
import numpy as np
# converting to lowercase
print(np.char.lower(['GEEKS', 'FOR']))
# converting to lowercase
print(np.char.lower('GEEKS'))
Output :
['geeks' 'for']
geeks

numpy.split() : This function returns a list of strings after breaking the given string by the specified separator.

# Python program explaining


# numpy.split() function

import numpy as np

# splitting a string
print(np.char.split('geeks for geeks'))

# splitting a string
print(np.char.split('geeks, for, geeks', sep = ','))

Output :
['geeks', 'for', 'geeks']
['geeks', 'for', 'geeks']

numpy.join() : This function is a string method and returns a string in which the elements of sequence have
been joined by str separator.

# Python program explaining


# numpy.join() function

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


73

import numpy as np

# splitting a string
print(np.char.join('-', 'geeks'))

# splitting a string
print(np.char.join(['-', ':'], ['geeks', 'for']))

Output
g-e-e-k-s
['g-e-e-k-s', 'g:e:e:k:s']

FUNCTION DESCRIPTION

It is used to remove all the leading and trailing spaces from a

numpy.strip() string.

It converts the first character of a string to capital (uppercase)

letter. If the string has its first character as capital, then it returns

numpy.capitalize() the original string.

It creates and returns a new string which is padded with the

numpy.center() specified character..

It is used to convert from one encoding scheme, in which

numpy.decode() argument string is encoded to the desired encoding scheme.

numpy.encode() Returns the string in the encoded form

Return an array with the elements of a left-justified in a string of

numpy.ljust() length width.

numpy.rjust() For each element in a, return a copy with the leading characters

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


74

removed.

For each element in a, return a copy with the leading and trailing

numpy.strip() characters removed.

numpy.lstrip() Convert angles from degrees to radians.

For each element in a, return a copy with the trailing characters

numpy.rstrip() removed.

numpy.partition() Partition each element in a around sep.

numpy.rpartition Partition (split) each element around the right-most separator.

For each element in a, return a list of the words in the string,

numpy.rsplit() using sep as the delimiter string.

It is used to convert the first character in each word to Uppercase

and remaining characters to Lowercase in string and returns new

numpy.title() string.

Returns the uppercased string from the given string. It converts

all lowercase characters to uppercase.If no lowercase characters

numpy.upper() exist, it returns the original string.

String Information –
numpy.count() : This function returns the number of occurrences of a substring in the given string.

# Python program explaining


# numpy.count() function

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


75

import numpy as np

a=np.array(['geeks', 'for', 'geeks'])

# counting a substring
print(np.char.count(a,'geek'))

# counting a substring
print(np.char.count(a, 'fo'))

Output :
[1, 0, 1]
[0, 1, 0]

numpy.rfind() : This function returns the highest index of the substring if found in given string. If not found
then it returns -1.

# Python program explaining


# numpy.rfind() function

import numpy as np

a=np.array(['geeks', 'for', 'geeks'])

# counting a substring
print(np.char.rfind(a,'geek'))

# counting a substring
print(np.char.rfind(a, 'fo'))
Output :
[0, -1, 0]
[-1, 0, -1]

numpy.isnumeric() : This function returns “True” if all characters in the string are numeric characters,
Otherwise, It returns “False”.

# Python program explaining


# numpy.isnumeric() function

import numpy as np

# counting a substring
print(np.char.isnumeric('geeks'))

# counting a substring
print(np.char.isnumeric('12geeks'))
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
76

Output :
False
False

FUNCTION DESCRIPTION

It returns the lowest index of the substring if it is found in given string.

numpy.find() If its is not found then it returns -1.

numpy.index() It returns the position of the first occurrence of substring in a string

It returns “True” if all characters in the string are alphabets, Otherwise,

numpy.isalpha() It returns “False”.

It returns true if all characters in a string are decimal. If all characters

numpy.isdecimal() are not decimal then it returns false.

It returns “True” if all characters in the string are digits, Otherwise, It

numpy.isdigit() returns “False”.

It returns “True” if all characters in the string are lowercase,

numpy.islower() Otherwise, It returns “False”.

Returns true for each element if there are only whitespace characters in

numpy.isspace() the string and there is at least one character, false otherwise.

Returns true for each element if the element is a titlecased string and

numpy.istitle() there is at least one character, false otherwise.

numpy.isupper() Returns true for each element if all cased characters in the string are

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


77

uppercase and there is at least one character, false otherwise.

Returns the highest index of the substring inside the string if substring

numpy.rindex() is found. Otherwise it raises an exception.

Returns True if a string starts with the given prefix otherwise returns

numpy.startswith() False.

String Comparison –
numpy.equal(): This function checks for string1 == string2 elementwise.

# Python program explaining


# numpy.equal() function

import numpy as np

# comparing a string elementwise


# using equal() method
a=np.char.equal('geeks','for')

print(a)

Output :
False

numpy.not_equal(): This function checks whether two string is unequal or not.

# Python program explaining


# numpy.unequal() function

import numpy as np

# comparing a string elementwise


# using unequal() method
a=np.char.unequal('geeks','for')

print(a)

Output :
True

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


78

numpy.greater(): This function checks whether string1 is greater than string2 or not.

# Python program explaining


# numpy.greater() function

import numpy as np

# comparing a string elementwise


# using greater() method
a=np.char.greater('geeks','for')

print(a)

Output :
True

FUNCTION DESCRIPTION

numpy.greater_equal() It checks whether string1 >= string2 or not.

numpy.less_equal() It checks whether string1 is <= string2 or not.

numpy.less() It check whether string1 is lesser than string2 or not.

Another material
1. numpy.char.lower()
This function returns an array with elements converted to lowercase. It calls str.lower for each element.
import numpy as np
print np.char.lower(['HELLO','WORLD'])
print np.char.lower('HELLO')
output
['hello' 'world']
hello

2. numpy.char.upper()
This function calls str.upper function on each element in an array to return the uppercase array
elements.
import numpy as np
print np.char.upper('hello')
print np.char.upper(['hello','world'])
output

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


79

HELLO
['HELLO' 'WORLD']
3. numpy.char.capitalize()
This function returns the copy of the string with the first letter capitalized.
import numpy as np
print np.char.capitalize('hello world')
output
Hello world
4. numpy.char.split()
This function returns a list of words in the input string. By default, a whitespace is used as a separator.
Otherwise the specified separator character is used to spilt the string.
import numpy as np
print np.char.split ('hello how are you?')
print np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep = ',')
output:
['hello', 'how', 'are', 'you?']
['TutorialsPoint', 'Hyderabad', 'Telangana']

5. numpy.char.replace()
This function returns a new copy of the input string in which all occurrences of the sequence of
characters is replaced by another given sequence.
import numpy as np
print np.char.replace ('He is a good boy', 'is', 'was')
output
He was a good boy
6. numpy.char.replace()
This function returns a new copy of the input string in which all occurrences of the sequence of
characters is replaced by another given sequence.
import numpy as np
print np.char.replace ('He is a good boy', 'is', 'was')
output
He was a good boy
7. numpy.char.split()

This function returns a list of words in the input string. By default, a whitespace is used as a separator.
Otherwise the specified separator character is used to spilt the string.
import numpy as np
print np.char.split ('hello how are you?')
print np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep = ',')
output
['hello', 'how', 'are', 'you?']
['TutorialsPoint', 'Hyderabad', 'Telangana']
8. numpy.char.capitalize()
This function returns the copy of the string with the first letter capitalized.
import numpy as np
print np.char.capitalize('hello world')

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


80

output
Hello world
9. numpy.char.center()
This function returns an array of the required width so that the input string is centered and padded on
the left and right with fillchar.
import numpy as np
# np.char.center(arr, width,fillchar)
print np.char.center('hello', 20,fillchar = '*')
output
*******hello********

10. numpy.char.title()
This function returns a title cased version of the input string with the first letter of each word
capitalized.
import numpy as np
print np.char.title('hello how are you?')
output
Hello How Are You?
11. numpy.char.add()
This function performs elementwise string concatenation.
import numpy as np
print 'Concatenate two strings:'
print np.char.add(['hello'],[' xyz'])
print '\n'

print 'Concatenation example:'


print np.char.add(['hello', 'hi'],[' abc', ' xyz'])
output
Concatenate two strings:
['hello xyz']

Concatenation example:
['hello abc' 'hi xyz']
12. numpy.char.multiply()
This function performs multiple concatenation.
import numpy as np
print np.char.multiply('Hello ',3)
output
Hello Hello Hello

9) NumPy Financial functions

Simple Financial functions routines

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


81

Name Description Syntax

fv() Compute the future value. numpy.fv(rate, nper, pmt, pv, when='end')
[source]

pv() Compute the present value. numpy.pv(rate, nper, pmt, fv=0.0, when='end')

npv() Returns the NPV (Net Present Value) of a numpy.npv(rate, values)


cash flow series.

pmt() Compute the payment against loan numpy.pmt(rate, nper, pv, fv=0, when='end')
principal plus interest.

ppmt() Compute the payment against loan numpy.ppmt(rate, per, nper, pv, fv=0.0,
principal. when='end')

ipmt Compute the interest portion of a numpy.ipmt(rate, per, nper, pv, fv=0.0,
payment. when='end')

irr The (IRR) function return the Internal numpy.irr(values)


Rate of Return.

mirr Modified internal rate of return. numpy.mirr(values, finance_rate,


reinvest_rate)

nper() Compute the number of periodic numpy.nper(rate, pmt, pv, fv=0, when='end')
payments.

rate() Compute the rate of interest per period. numpy.rate(nper, pmt, pv, fv, when='end',
guess=0.1, tol=1e-06, maxiter=100)

Functions
fv(rate, nper, pmt, pv[, when]) Compute the future value.
ipmt(rate, per, nper, pv[, fv, when]) Compute the interest portion of a payment.
irr(values) Return the Internal Rate of Return (IRR).
mirr(values, finance_rate, reinvest_rate) Modified internal rate of return.
nper(rate, pmt, pv[, fv, when]) Compute the number of periodic payments.
Returns the NPV (Net Present Value) of a cash
npv(rate, values)
flow series.
Compute the payment against loan principal plus
pmt(rate, nper, pv[, fv, when])
interest.
ppmt(rate, per, nper, pv[, fv, when]) Compute the payment against loan principal.
pv(rate, nper, pmt[, fv, when]) Compute the present value.
rate(nper, pmt, pv, fv[, when, guess, tol, …]) Compute the rate of interest per period.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


82

1. numpy.fv() function
The fv() function is used to compute the future value.
Syntax:
numpy.fv(rate, nper, pmt, pv, when='end')[source]
Given:
 a present value, pv
 an interest rate compounded once per period, of which there are
 nper total
 a (fixed) payment, pmt, paid either
 at the beginning (when = {'begin', 1}) or the end (when = {'end', 0}) of each period
Version: 1.15.0
Parameter:
Name Description Required /
Optional

rate Rate of interest as decimal (not per cent) per period Required
scalar or array_like of shape(M, )

nper Number of compounding periods Required


scalar or array_like of shape(M, )

pmt Payment Required


scalar or array_like of shape(M, )

pv Present value Required


scalar or array_like of shape(M, )

when When payments are due ('begin' (1) or 'end' (0)). Defaults to Optional
{'end', 0}.
{{'begin', 1}, {'end', 0}}, {string, int}

Return value: the value at the end of the nper periods


Returns: out : ndarray
Future values. If all input is scalar, returns a scalar float. If any input is array_like, returns future values for
each input element.
If multiple inputs are array_like, they all must have the same shape.
Notes:
The future value is computed by solving the equation:

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


83

fv +
pv*(1+rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
or, when rate == 0:
fv + pv + pmt * nper == 0
NumPy.fv() method Example-1:
What is the future value after 10 years of saving $200 now, with an additional monthly savings of $200.
Assume the interest rate is 6% (annually) compounded monthly?

>>> import numpy as np


>>> np.fv(0.06/12, 10*12, -200, -200)
Copy
Output:
33139.748708098065
1.

NumPy.fv() method Example-2:


By convention, the negative sign represents cash flow out (i.e. money not available today). Thus, saving
$200 a month at 6% annual interest leads to $33,139.75 available to spend in 10 years.
If any input is array_like, returns an array of equal shape. Let's compare different interest rates from the
example above.
import numpy as np
x = np.array((0.06, 0.06, 0.07))/12
np.fv(x, 10*12, -200, -200)
Copy
Output:
array([33139.7487081 , 33139.7487081 , 35018.89376205])

2. numpy.pv() function
The pv() function is used to compute the present value.
Syntax:
numpy.pv(rate, nper, pmt, fv=0.0, when='end')
Given:
 a future value, fv
 an interest rate compounded once per period, of which there are
 nper total
 a (fixed) payment, pmt, paid either
 at the beginning (when = {'begin', 1}) or the end (when = {'end', 0}) of each period

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


84

Version: 1.15.0

Parameter:
Name Description Required /
Optional

rate Rate of interest (per period) Required


array_like

nper Number of compounding periods Required


array_like

pmt Payment Required


array_like

fv Future value Optional


array_like

when When payments are due ('begin' (1) or 'end' (0)) Optional
{{'begin', 1}, {'end', 0}}, {string, int}

Return value: the value now


Returns: out : ndarray, float
Present value of a series of payments or investments.
Notes:
The present value is computed by solving the equation:
fv + pv*(1+rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0
or, when rate == 0:
fv + pv + pmt * nper = 0
for pv, which is then returned.
NumPy.pv() method Example-1:
What is the present value (e.g., the initial investment) of an investment that needs to total $33139.75 after
10 years of saving $200 every month?
Assume the interest rate is 5% (annually) compounded monthly.
>>> import numpy as np
>>> np.pv(0.06/12, 10*12, -200, 33139.75)
Copy
Output:
-200.0007100715939

NumPy.pv() method Example-2:


SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
85

By convention, the negative sign represents cash flow out (i.e., money not available today).
Thus, to end up with $33139.75 in 10 years saving $200 a month at 6% annual interest,one's initial deposit
should also be $200.
If any input is array_like, pv returns an array of equal shape. Let's compare different interest rates in the
example above:
>>> import numpy as np
>>> x = np.array((0.06, 0.04, 0.03))/12
>>> np.pv(x, 10*12, -200, 33139.75)
Copy
Output:
array([ -200.00071007, -2474.98535444, -3847.37286647])

So, to end up with the same $33139.75 under the same $200 per month "savings plan," for annual interest
rates of 4% and 3%, one would need initial investments of $2474.99 and $3847.37, respectively.

3. numpy.npv() function
The npv() function is used to get the NPV (Net Present Value) of a cash flow series.
Syntax:
numpy.npv(rate, values)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

rate The discount rate. Required


scalar

values The values of the time series of cash flows. The (fixed) Required
time interval between cash flow "events" must be the same
as that for which rate is given (i.e., if rate is per year, then
precisely a year is understood to elapse between each cash
flow event). By convention, investments or "deposits" are
negative, income or "withdrawals" are positive; values
must begin with the initial investment, thus values[0] will
typically be negative.
array_like, shape(M, )

Returns: out : float
The NPV of the input cash flow series values at the discount rate.
Notes:
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
86

Returns the result of: [G]


\sum_{t=0}^{M-1}{\frac{values_t}{(1+rate)^{t}}}
NumPy.npv() method Example:

>>> import numpy as np


>>> np.npv(0.281,[-200, 39, 59, 55, 20])
Copy
Output:
-100.00847859163845

4. numpy.pmt() function
The pmt() function is used to compute the payment against loan principal plus interest.
Syntax:
numpy.pmt(rate, nper, pv, fv=0, when='end')
Given:
 a present value, pv (e.g., an amount borrowed)
 a future value, fv (e.g., 0)
 an interest rate compounded once per period, of which there are
 nper total
 and (optional) specification of whether payment is made at the beginning (when = {'begin', 1}) or
the end (when = {'end', 0}) of each period
Version: 1.15.0
Parameter:
Name Description Required /
Optional

rate Rate of interest (per period) Required


array_like

nper Number of compounding periods Required


array_like

pv Present value Required


array_like

fv Future value (default = 0) Optional


array_like

when When payments are due ('begin' (1) or 'end' Required


(0))

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


87

{{'begin', 1}, {'end', 0}}, {string, int}

Return value: the (fixed) periodic payment.


Returns: out : ndarray
Payment against loan plus interest.
If all input is scalar, returns a scalar float. If any input is array_like, returns payment for each input element.
If multiple inputs are array_like, they all must have the same shape.
Notes:
The payment is computed by solving the equation:
fv +
pv*(1 + rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
or, when rate == 0:
fv + pv + pmt * nper == 0
for pmt.
Note that computing a monthly mortgage payment is only one use for this function. For example, pmt
returns the periodic deposit one must make to achieve a specified future balance given an initial deposit, a
fixed, periodically compounded interest rate, and the total number of periods.

NumPy.pmt() method Example:


What is the monthly payment needed to pay off a $100,000 loan in 12 years at an annual interest rate of
8.5%?
>>> import numpy as np
>>> np.pmt(0.085/12, 12*12, 100000)
Copy
Output:
-1110.0555643145096
In order to pay-off (i.e., have a future-value of 0) the $100,000 obtained today, a monthly payment of
$1,110.05 would be required. Note that this example illustrates usage of fv having a default value of 0.

5. numpy.ppmt() function
The ppmt() function is used to compute the payment against loan principal.
Syntax:
numpy.ppmt(rate, per, nper, pv, fv=0.0, when='end')
Version: 1.15.0
Parameter:
Name Description Required /

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


88

Optional

rate Rate of interest (per period) Required


array_like

per Amount paid against the loan changes. Required


The per is the period of interest.
array_like, int

nper Number of compounding periods Required


array_like

pv Present value Required


array_like

fv Future value Optional


array_like

when When payments are due ('begin' (1) or 'end' (0)) Required
{{'begin', 1}, {'end', 0}}, {string, int}

NumPy.ppmt() method Example:


What is the monthly payment needed to pay off a $100,000 loan in 12 years at an annual interest rate of
8.5%?
>>> import numpy as np
>>> np.ppmt(0.085/12, 1, 12*12, 100000)
Copy
Output:
-401.72223098117627

6. numpy.ipmt() function
The ipmt() function is used to compute the interest portion of a payment.
Syntax:
numpy.ipmt(rate, per, nper, pv, fv=0.0, when='end')
Version: 1.15.0
Parameter:
Name Description Required /
Optional

rate Rate of interest as decimal (not per cent) per period Required
scalar or array_like of shape(M, )

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


89

per Interest paid against the loan changes during the life or the loan. Required
The per is the payment period to calculate the interest amount.
scalar or array_like of shape(M, )

nper Number of compounding periods Required


scalar or array_like of shape(M, )

pv Present value Required


scalar or array_like of shape(M, )

fv Future value Optional


scalar or array_like of shape(M, )

when When payments are due ('begin' (1) or 'end' (0)). Defaults to {'end', Optional
0}.
{{'begin', 1}, {'end', 0}}, {string, int}

Returns: out : ndarray
Interest portion of payment. If all input is scalar, returns a scalar float. If any input is array_like, returns
interest payment for each input element.
If multiple inputs are array_like, they all must have the same shape.
Notes:
The total payment is made up of payment against principal plus interest.
pmt = ppmt + ipmt
NumPy.ipmt() method Example - 1:

>>> import numpy as np


>>> np.allclose(ipmt + ppmt, pmt)
Copy
Output:
True
NumPy.ipmt() method Example - 2:
What is the amortization schedule for a 1 year loan of $10000 at 8.5% interest per year compounded
monthly?
>>> import numpy as np
>>> principal = 10000.00
>>> per = np.arange(1*12) + 1 # The 'per' variable represents the periods of the loan. Remember that
financial equations start the period count at 1!
>>> ipmt = np.ipmt(0.0850/12, per, 1*12, principal)
>>> ppmt = np.ppmt(0.0850/12, per, 1*12, principal)
>>> pmt = np.pmt(0.0850/12, 1*12, principal) # Each element of the sum of the 'ipmt' and 'ppmt' arrays
should equal 'pmt'.
>>> fmt = '{0:2d} {1:8.2f} {2:8.2f} {3:8.2f}'
>>> for payment in per:
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
90

... index = payment - 1


... principal = principal + ppmt[index]
... print(fmt.format(payment, ppmt[index], ipmt[index], principal))
Output:
1 -801.36 -70.83 9198.64
2 -807.04 -65.16 8391.59
3 -812.76 -59.44 7578.84
4 -818.51 -53.68 6760.32
5 -824.31 -47.89 5936.01
6 -830.15 -42.05 5105.86
7 -836.03 -36.17 4269.83
8 -841.95 -30.24 3427.88
9 -847.92 -24.28 2579.96
10 -853.92 -18.27 1726.03
11 -859.97 -12.23 866.06
12 -866.06 -6.13 -0.00

NumPy.ipmt() method Example - 3:


What is the amortization schedule for a 1 year loan of $10000 at 8.5% interest per year compounded
monthly?
>>> import numpy as np
>>> principal = 10000.00
>>> per = np.arange(1*12) + 1 # The 'per' variable represents the periods of the loan. Remember that
financial equations start the period count at 1!
>>> ipmt = np.ipmt(0.0850/12, per, 1*12, principal)
>>> ppmt = np.ppmt(0.0850/12, per, 1*12, principal)
>>> pmt = np.pmt(0.0850/12, 1*12, principal) # Each element of the sum of the 'ipmt' and 'ppmt' arrays
should equal 'pmt'.
>>> interestpd = np.sum(ipmt)
>>> np.round(interestpd, 2)
Output:
-466.37
NumPy.ipmt() method Example - 4:
What is the amortization schedule for a 1 year loan of $10000 at 8.5% interest per year compounded
monthly?
>>> import numpy as np
>>> principal = 10000.00
>>> per = np.arange(1*12) + 1 # The 'per' variable represents the periods of the loan. Remember that
financial equations start the period count at 1!
>>> ipmt = np.ipmt(0.0850/12, per, 1*12, principal)
>>> interestpd = np.sum(ipmt)
>>> np.round(interestpd, 3)
Output:

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


91

-466.374

7. numpy.irr() function
The irr() function is used to get the Internal Rate of Return (IRR).
This is the "average" periodically compounded rate of return that gives a net present value of 0.0; for a more
complete explanation, see Notes below.
decimal.Decimal type is not supported.
Syntax:
numpy.irr(values)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

values Input cash flows per time period. By convention, net Required
"deposits" are negative and net "withdrawals" are
positive.
Thus, for example, at least the first element of values,
which represents the initial investment, will typically be
negative.
array_like, shape(N,)

Returns: out : float
Internal Rate of Return for periodic input values.
Notes:
The IRR is perhaps best understood through an example (illustrated using np.irr in the Examples section
below).
Suppose one invests 200 units and then makes the following withdrawals at regular (fixed) intervals: 78,
118, 111, 40.
Assuming the ending value is 0, one's 200 unit investment yields 347 units; however,
due to the combination of compounding and the periodic withdrawals, the "average" rate of return is neither
simply 0.73/4 nor (1.73)^0.25-1.
Rather, it is the solution (for r) of the equation:
-200 + \frac{78}{1+r} + \frac{118}{(1+r)^2} + \frac{110}{(1+r)^3} +
\frac{40}{(1+r)^4} = 0
In general, for values = [v_0, v_1, ... v_M], irr is the solution of the equation: [G]
\sum_{t=0}^M{\frac{v_t}{(1+irr)^{t}}} = 0
NumPy.irr() method Example-1:
>>> import numpy as np

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


92

>>> round(np.irr([-200, 78, 118, 111, 40]), 5)


Output:
0.28239

NumPy.irr() method Example-2:


>>> import numpy as np
>>> round(np.irr([-200, 0, 0, 74]), 4)
Output:
-0.2821
NumPy.irr() method Example-3:
>>> import numpy as np
>>> round(np.irr([-200, 200, 0, -7]), 4)
Output:
-0.0378
NumPy.irr() method Example-4:
>>> import numpy as np
>>> round(np.irr([-200, 200, 0, 7]), 4)
Output:
0.0328
NumPy.irr() method Example-5:
>>> import numpy as np
>>> round(irr([-5, 10.5, 1, -8, 1]), 5)
Copy
Output:
0.0886

8. numpy.mirr() function
The mirr() function is used to modify internal rate of return.
Syntax:
numpy.mirr(values, finance_rate, reinvest_rate)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

values Cash flows (must contain at least one positive and one Required
negative value) or nan is returned.
The first value is considered a sunk cost at time zero.
array_like

finance_rate Interest rate paid on the cash flows Required

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


93

scalar

reinvest_rate Interest rate received on the cash flows upon reinvestment Required
scalar

Returns: out : float
Modified internal rate of return
NumPy.mirr() method Example:
If you investment $1000 and withdrawals at regular interval $100, $50, $10 and $15. Here finance_rate .34
and reinvest_rate .21, Then the calculate modified internal rate of return (mirr)?
>>> import numpy as np
>>> np.mirr([-1000, 100, 50, 10, 15], .34, .21)
Copy
Output:
-0.2742274708267268

9. numpy.nper() function
The nper() function is used to compute the number of periodic payments.
decimal.Decimal type is not supported.
Syntax:
numpy.nper(rate, pmt, pv, fv=0, when='end')
Version: 1.15.0
Parameter:
Name Description Required /
Optional

rate Rate of interest (per period) Required


array_like

pmt Payment Required


array_like

pv Present value Required


array_like

fv Future value Optional


array_like

when When payments are due ('begin' (1) or 'end' Optional


(0))
{{'begin', 1}, {'end', 0}}, {string, int}

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


94

Notes:
The number of periods nper is computed by solving the equation:
fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate*((1+rate)**nper-1) = 0
but if rate = 0 then:
fv + pv + pmt*nper = 0
NumPy.nper() method Example-1:
If you only had $200/month to pay towards the loan, how long would it take to pay-off a loan of $10,000 at
8% annual interest?
>>> import numpy as np
>>> print(np.round(np.nper(0.08/12, -200, 10000), 2))
Copy
Output:
61.02
NumPy.nper() method Example-2:
So, over 64 months would be required to pay off the loan.
The same analysis could be done with several different interest rates and/or payments and/or total amounts
to produce an entire table.
>>> import numpy as np
>>> np.nper(*(np.ogrid[0.07/12: 0.08/12: 0.01/12,
... -150 : -99 : 50 ,
... 8000 : 9001 : 1000]))
Copy
Output:
array([[[ 64.07334877, 74.06368256],
[108.07548412, 127.99022654]],

[[ 66.12443902, 76.87897353],
[114.70165583, 137.90124779]]])

10. numpy.rate() function


The rate() function is used to compute the rate of interest per period.
Syntax:
numpy.rate(nper, pmt, pv, fv, when='end', guess=0.1, tol=1e-06, maxiter=100)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

nper Number of compounding periods Required


array_like

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


95

pmt Payment Required


array_like

pv Present value Required


array_like

fv Future value Required


array_like

when When payments are due ('begin' (1) or 'end' (0)) Optional
{{'begin', 1}, {'end', 0}}, {string, int}

guess Starting guess for solving the rate of interest, Optional


default 0.1
Number

tol Required tolerance for the solution, default 1e-6 Optional


Number

maxiter Maximum iterations in finding the solution Optional


int

Notes:
The rate of interest is computed by iteratively solving the (non-linear) equation:
fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0
NumPy.rate() method Example-1:
>>> import numpy as np
>>> np.rate(8, 10000, 500, 200)
Copy
Output:
-2.0184122884653117
Rate is 2.018 per period.

10) NumPy Functional Programming


Functional programming routines
Name Description Syntax

apply_along_axis() Apply a function to 1-D slices numpy.apply_along_axis(func1d, axis, arr,


along the given axis. *args, **kwargs)

apply_over_axes() Apply a function repeatedly numpy.apply_over_axes(func, a, axes)


over multiple axes.

vectorize() Generalized function class. class numpy.vectorize(pyfunc, otypes=None,

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


96

doc=None, excluded=None, cache=False,


signature=None)

frompyfunc() Takes an arbitrary Python numpy.frompyfunc(func, nin, nout)


function and returns a NumPy
ufunc.

piecewise() Evaluate a piecewise-defined numpy.piecewise(x, condlist, funclist, *args,


function. **kw)

1. numpy.apply_along_axis() function
The apply_along_axis() function is used for apply a function to 1-D slices along the given axis.
Execute func1d(a, *args) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.
This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii, jj, and kk to
a tuple of indices:
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
f = func1d(arr[ii + s_[:,] + kk])
Nj = f.shape
for jj in ndindex(Nj):
out[ii + jj + kk] = f[jj]
Equivalently, eliminating the inner loop, this can be expressed as:
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
Syntax:
numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

func1d This function should accept 1-D arrays. Required


It is applied to 1-D slices of arr along the specified
axis.
function (M,) -> (Nj…)

axis Axis along which arr is sliced. Required


integer

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


97

arr Input array. Required


ndarray (Ni…, M, Nk…)

args Additional arguments to func1d. Required


any

kwargs Additional named arguments to func1d. Required


any

Returns: out : ndarray (Ni…, Nj…, Nk…)


The output array. The shape of out is identical to the shape of arr, except along the axis dimension.
This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d.
So if func1d returns a scalar out will have one fewer dimensions than arr.
NumPy.apply_along_axis() method Example-1:
>>> import numpy as np
>>> def my_func(x): return (x[0] + x[-1]) * 0.5 # """Average first and last element of a 1-D array"""
>>> y = np.array([[2,4,6], [1,3,5], [9,7,8]])
>>> np.apply_along_axis(my_func, 0, y)
Copy
Output:
array([5.5, 5.5, 7. ])

NumPy.apply_along_axis() method Example-2:


>>> import numpy as np
>>> def my_func(x): return (x[0] + x[-1]) * 0.5 #"""Average first and last element of a 1-D array"""
>>> y = np.array([[2,4,6], [1,3,5], [9,7,8]])
>>> np.apply_along_axis(my_func, 1, y)
Copy
Output:
array([4. , 3. , 8.5])
For a function that returns a 1D array, the number of dimensions in outarr is the same as arr.
NumPy.apply_along_axis() method Example-3:
>>> import numpy as np
>>> y = np.array([[2,4,6], [1,3,5], [9,7,8]])
>>> np.apply_along_axis(sorted, 1, y)
Copy
Output:
array([[2, 4, 6],
[1, 3, 5],
[7, 8, 9]])
For a function that returns a higher dimensional array, those dimensions are inserted in place of the axis
dimension.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


98

NumPy.apply_along_axis() method Example-4:


>>> import numpy as np
>>> y = np.array([[2,4,6], [1,3,5], [9,7,8]])
>>> np.apply_along_axis(np.diag, -1, y)
Copy
Output:
array([[[2, 0, 0],
[0, 4, 0],
[0, 0, 6]],

[[1, 0, 0],
[0, 3, 0],
[0, 0, 5]],

[[9, 0, 0],
[0, 7, 0],
[0, 0, 8]]])

2. numpy.apply_over_axes() function
The apply_over_axes() function is used to apply a function repeatedly over multiple axes.
func is called as res = func(a, axis), where axis is the first element of axes.
The result res of the function call must have either the same dimensions as a or one less dimension.
If res has one less dimension than a, a dimension is inserted before axis.
The call to func is then repeated for each axis in axes, with res as the first argument.
Syntax:
numpy.apply_over_axes(func, a, axes)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

func This function must take two arguments, func(a, axis). Required
function

a Input array. Required


array_like

axes Axes over which func is applied; the elements must be integers. Required
array_like

Returns: apply_over_axis : ndarray

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


99

The output array. The number of dimensions is the same as a, but the shape can be different.
This depends on whether func changes the shape of its output with respect to its input.
Notes:
This function is equivalent to tuple axis arguments to reorderable ufuncs with keepdims=True.
NumPy.apply_over_axes() method Example:
>>> import numpy as np
>>> x = np.arange(24).reshape(3,2,4)
>>> x
Copy
Output:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],

[[ 8, 9, 10, 11],
[12, 13, 14, 15]],

[[16, 17, 18, 19],


[20, 21, 22, 23]]])

Sum over axes 0 and 2. The result has same number of dimensions as the original array:
>>> import numpy as np
>>> x = np.arange(24).reshape(3,2,4)
>>> np.apply_over_axes(np.sum, x, [0,2])
Copy
Output:
array([[[114],
[162]]])

Tuple axis arguments to ufuncs are equivalent:


>>> import numpy as np
>>> x = np.arange(24).reshape(3,2,4)
>>> np.sum(x, axis=(0,2), keepdims=True)
Copy
Output:
array([[[114],
[162]]])

3. numpy.vectorize() function
The vectorize() function is used to generalize function class.
Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns
an single or tuple of numpy array as output.

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


100

The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map
function, except it uses the broadcasting rules of NumPy.
Syntax:
class numpy.vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

pyfunc A python function or method. Required


callable

otypes The output data type. It must be specified as either a string of Optional
typecode characters or a list of data type specifiers.
There should be one data type specifier for each output.
str or list of dtypes

doc The docstring for the function. If None, the docstring will be Optional
the pyfunc.__doc__.
str

excluded Set of strings or integers representing the positional or Optional


keyword arguments for which the function will not be
vectorized.
These will be passed directly to pyfunc unmodified.
set

cache If True, then cache the first function call that determines the Optional
number of outputs if otypes is not provided.
bool

signature Generalized universal function signature, e.g., (m,n),(n)->(m) Optional


for vectorized matrix-vector multiplication.
If provided, pyfunc will be called with (and expected to
return) arrays with shapes given by the size of corresponding
core dimensions.
By default, pyfunc is assumed to take scalars as input and
output.
string

Returns: vectorized : callable
Vectorized function.
Notes:

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


101

The vectorize function is provided primarily for convenience, not for performance.
The implementation is essentially a for loop.
If otypes is not specified, then a call to the function with the first argument will be used to determine the
number of outputs.
The results of this call will be cached if cache is True to prevent calling the function twice.
However, to implement the cache, the original function must be wrapped which will slow down subsequent
calls, so only do this if your function is expensive.
The new keyword argument interface and excluded argument support further degrades performance.
NumPy.vectorize() method Example:
>>> import numpy as np
>>> def my_func(x, y):
"Return x-y if x>y, otherwise return x+y"
if x > y:
return x - y
else:
return x + y
>>> vec_func = np.vectorize(my_func)
>>> vec_func([2, 4, 6, 8], 4)
Copy
Output:
array([6, 8, 2, 4])

The docstring is taken from the input function to vectorize unless it is specified:
>>> import numpy as np
>>> def my_func(x, y):
vec_func.__doc__
'Return a-b if x>y, otherwise return x+y'
>>> vec_func = np.vectorize(my_func, doc="nareshresource 'tutorial'")
>>> vec_func.__doc__
Copy
Output:
"nareshresource 'tutorial'"
The output type is determined by evaluating the first element of the input, unless it is specified:
>>> import numpy as np
>>> out = vec_func([2, 4, 6, 8], 4)
>>> type(out[0])
Copy
Output:
numpy.float64
>>> import numpy as np
>>> def my_func(x, y):
vec_func = np.vectorize(my_func, otypes=[float])
>>> out = vec_func([2, 4, 6, 8], 4)
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
102

>>> type(out[0])
Copy
Output:
numpy.float64
The excluded argument can be used to prevent vectorizing over certain arguments.
This can be useful for array-like arguments of a fixed length such as the coefficients for a polynomial as in
polyval:
>>> import numpy as np
>>> def my_polyval(a, b):
_a = list(a)
res = _a.pop(0)
while _a:
res = res*b + _a.pop(0)
return res
>>> vec_polyval = np.vectorize(my_polyval, excluded=['a'])
>>> vec_polyval(a=[1, 3, 5], b=[0, 1])
Copy
Output:
array([5, 9])
Positional arguments may also be excluded by specifying their position:
>>> vec_polyval.excluded.add(0)
>>> vec_polyval([1, 3, 5], b=[0, 1])
Copy
Output:
array([5, 9])
The signature argument allows for vectorizing functions that act on non-scalar arrays of fixed length.
For example, you can use it for a vectorized calculation of Pearson correlation coefficient and its p-value:
>>> import scipy.stats
>>> pearsonr = np.vectorize(scipy.stats.pearsonr,
signature='(n),(n)->(),()')
>>> pearsonr([[0, 2, 4, 6]], [[1, 2, 4, 6], [6, 4, 2, 1]])
Copy
Output:
(array([ 1., -1.]), array([ 0., 0.]))
Or for a vectorized convolution:
>>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')
>>> convolve(np.eye(6), [1, 3, 5])
Copy
Output:
array([[1., 3., 5., 0., 0., 0., 0., 0.],
[0., 1., 3., 5., 0., 0., 0., 0.],
[0., 0., 1., 3., 5., 0., 0., 0.],
[0., 0., 0., 1., 3., 5., 0., 0.],

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


103

[0., 0., 0., 0., 1., 3., 5., 0.],


[0., 0., 0., 0., 0., 1., 3., 5.]])

4. numpy.frompyfunc() function
The frompyfunc() function is used to take an arbitrary Python function and returns a NumPy ufunc.
Can be used to add broadcasting to a built-in Python function.
Syntax:
numpy.frompyfunc(func, nin, nout)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

func An arbitrary Python function. Required


Python function object

nin The number of input arguments. Required


int

nout The number of objects returned by func. Required


int

Returns: out : ufunc
Returns a NumPy universal function (ufunc) object.
Notes:
The returned ufunc always returns PyObject arrays.
NumPy.frompyfunc() method Example-1:
Use frompyfunc to add broadcasting to the Python function oct:
>>> import numpy as np
>>> array = np.frompyfunc(oct, 1, 1)
>>> array(np.array((25, 50, 75)))
Copy
Output:
array(['0o31', '0o62', '0o113'], dtype=object)
NumPy.frompyfunc() method Example-2:
Use frompyfunc to add broadcasting to the Python function oct:
>>> import numpy as np
>>> array = np.frompyfunc(oct, 1, 1)
>>> np.array((oct(25), oct(50), oct(75))) # for comparison
Copy
Output:
array(['0o31', '0o62', '0o113'], dtype='<U5')
SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY
104

numpy.piecewise() function
The piecewise() function is used to evaluate a piecewise-defined function.
Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its
condition is true.
Syntax:
numpy.piecewise(x, condlist, funclist, *args, **kw)
Version: 1.15.0
Parameter:
Name Description Required /
Optional

x The input domain. Required


ndarray or scalar

condlist Each boolean array corresponds to a function in Required


funclist.
Wherever condlist[i] is True, funclist[i](x) is used as
the output value.
Each boolean array in condlist selects a piece of x, and
should therefore be of the same shape as x.
The length of condlist must correspond to that of
funclist. If one extra function is given, i.e. if
len(funclist) == len(condlist) + 1,
then that extra function is the default value, used
wherever all conditions are false.
list of bool arrays or bool scalars

funclist Each function is evaluated over x wherever its Required


corresponding condition is True.
It should take a 1d array as input and give an 1d array
or a scalar value as output.
If, instead of a callable, a scalar is provided then a
constant function (lambda x: scalar) is assumed.
list of callables, f(x,*args,**kw), or scalars

args Any further arguments given to piecewise are passed Optional


to the functions upon execution, i.e.,
if called piecewise(..., ..., 1, 'a'), then each function is
called as f(x, 1, 'a').
tuple

kw Keyword arguments used in calling piecewise are Optional


passed to the functions upon execution, i.e.,
if called piecewise(..., ..., alpha=1), then each function

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY


105

is called as f(x, alpha=1).


dict

Returns: out : ndarray
The output is the same shape and type as x and is found by calling the functions in funclist on the
appropriate portions of x,
as defined by the boolean arrays in condlist. Portions not covered by any condition have a default value of
0.
Notes:
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the
corresponding condition from condlist.
The result is:
|--
|funclist[0](x[condlist[0]])
out = |funclist[1](x[condlist[1]])
|...
|funclist[n2](x[condlist[n2]])
|--
NumPy.piecewise() method Example:
Define the sigma function, which is -1 for x < 0 and +1 for x >= 0.
>>> import numpy as np
>>> x = np.linspace(-3.5, 3.5, 5)
>>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
Copy
Output:
array([-1., -1., -1., 1., 1., 1.])
Define the absolute value, which is -x for x <0 and x for x >= 0.
>>> import numpy as np
>>> x = np.linspace(-3.5, 3.5, 5)
>>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
Copy
Output:
array([3.5 , 1.75, 0. , 1.75, 3.5 ])
Apply the same function to a scalar value.
>>> import numpy as np
>>> x = np.linspace(-3.5, 3.5, 5)
>>> y = -6
>>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
Copy
Output:
array(6)

SRI VASAVI INSTITUTE OF ENGINEERING & TECHNOLOGY

You might also like