Professional Documents
Culture Documents
11.NUMPY Lab File (R20)
11.NUMPY Lab File (R20)
11.NUMPY Lab File (R20)
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
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
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
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.
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.
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
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
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
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).
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 .
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.
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.
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:
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.
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.
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.
print(arr)
Output:
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
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)
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)
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)
[ 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
>>> 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
x = random.randint(100)
print(x)
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])
x = random.rand()
print(x)
Output:
0.3420593363265507
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
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
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]
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
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
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))
output:
Program to demonstrate the len() method in python
The given array is as follows:
[2, 'educba', 3, 4.5]
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’>
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
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,2],[3,4],[5,6]])
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.'
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]]
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 '\n'
b = np.resize(a, (3,2))
Second array:
[[1 2]
[3 4]
[5 6]]
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
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:
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
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])
#Working on 1D
arr = geek.arange(5)
print("arr : \n", arr)
print("Shape : ", arr.shape)
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,)
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
>>> 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)
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
np.concatenate((a, b), axis=0)
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)
[7],
[5],
[7],
[9]])
Example 3
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))
>>> 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))
[[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
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
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])
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_sqrt = np.sqrt(arr)
print(arr_sqrt)
Output:
[1. 3. 5. 7.]
Example Codes: numpy.sqrt() With out Parameter
import numpy as np
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_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
x = np.sin(arr)
print(x)
Output
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])
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
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 np.degrees(inv)
print '\n'
Inverse of cos:
[ 0. 0.52359878 0.78539816 1.04719755 1.57079633]
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
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
out_array = np.log(in_array)
print ("Output array : ", out_array)
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:
>>> np.dot(3, 4)
Output
12
Neither argument is complex-conjugated:
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
p = [1, 2, 3]
gfg = geek.roots(p)
print (gfg)
Output :
[-1.+1.41421356j -1.-1.41421356j]
Example 3
# importing numpy as geek
p = [3.2, 2, 1]
gfg = geek.roots(p)
print (gfg)
Output :
[-0.3125+0.46351241j -0.3125-0.46351241j]
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
[5 6 7]
6.0
Example 1
# 1D array
arr = [20, 2, 7, 1, 34]
Output :
arr : [20, 2, 7, 1, 34]
mean of arr : 12.8
Example 3
# 2D array
arr = [[14, 17, 12, 33, 44],
[15, 6, 27, 8, 19],
[23, 2, 54, 1, 4, ]]
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
# 1D array
arr = [20, 2, 7, 1, 34]
Output :
arr : [20, 2, 7, 1, 34]
median of arr : 7.0
Example 2:
# 2D array
arr = [[14, 17, 12, 33, 44],
[15, 6, 27, 8, 19],
[23, 2, 54, 1, 4, ]]
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
out_arr : [0 1 2]
median of arr, axis = 1 : [17 15 4]
Example 3:
b=ppool.array([12,13,16,18,19,22])
print(ppool.median(b))
Output:
14.0
17.0
Examples
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
0.45000005
>>> 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.
[ 0.99256089, 1. , -0.76492172],
[-0.68080986, -0.76492172, 1. ]])
In [1]:
import numpy as np
import pandas as pd
Numpy Data Types
Numpy has the following data types:
int
float
complex
bool
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',
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
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))
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
.
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)
print a
The output is as follows −
[ 1.+0.j, 2.+0.j, 3.+0.j]
(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.
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
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
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
print(arr)
print('number of dimensions :', arr.ndim)
output
[[[[[1 2 3 4]]]]]
number of dimensions : 5
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.
numpy.split() : This function returns a list of strings after breaking the given string by the specified separator.
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.
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
numpy.strip() string.
letter. If the string has its first character as capital, then it returns
numpy.rjust() For each element in a, return a copy with the leading characters
removed.
For each element in a, return a copy with the leading and trailing
numpy.rstrip() removed.
numpy.title() string.
String Information –
numpy.count() : This function returns the number of occurrences of a substring in the given string.
import numpy as np
# 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.
import numpy as np
# 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”.
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
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.isupper() Returns true for each element if all cased characters in the string are
Returns the highest index of the substring inside the string if substring
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.
import numpy as np
print(a)
Output :
False
import numpy as np
print(a)
Output :
True
numpy.greater(): This function checks whether string1 is greater than string2 or not.
import numpy as np
print(a)
Output :
True
FUNCTION DESCRIPTION
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
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')
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'
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
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')
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')
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.
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, )
when When payments are due ('begin' (1) or 'end' (0)). Defaults to Optional
{'end', 0}.
{{'begin', 1}, {'end', 0}}, {string, int}
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?
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
Version: 1.15.0
Parameter:
Name Description Required /
Optional
when When payments are due ('begin' (1) or 'end' (0)) Optional
{{'begin', 1}, {'end', 0}}, {string, int}
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
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
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
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 /
Optional
when When payments are due ('begin' (1) or 'end' (0)) Required
{{'begin', 1}, {'end', 0}}, {string, int}
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, )
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, )
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:
-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
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
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
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]]])
when When payments are due ('begin' (1) or 'end' (0)) Optional
{{'begin', 1}, {'end', 0}}, {string, 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.
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
[[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
axes Axes over which func is applied; the elements must be integers. Required
array_like
Returns: apply_over_axis : ndarray
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]],
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]]])
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.
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
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
cache If True, then cache the first function call that determines the Optional
number of outputs if otypes is not provided.
bool
Returns: vectorized : callable
Vectorized function.
Notes:
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.],
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
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
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)