Ch - 2 Advance Python
Ch - 2 Advance Python
Sem - 6
2 Python Numpy
Topics Covered
NumPy Introduction:
• NumPy is a Python package. It stands for 'Numerical Python'.
• It is a library consisting of multidimensional array objects and a collection of routines
for processing of array.
• NumPy is a Python library and is written partially in Python, but most of the parts that
require fast computation are written in C or C++.
• NumPy is a general-purpose array-processing package.
• It provides a high-performance multidimensional array object, and tools for working
with these arrays.
• It is the fundamental package for scientific computing with Python.
• Besides its obvious scientific uses, Numpy can also be used as an efficient multi-
dimensional container of generic data.
• Numeric, the ancestor of NumPy, was developed by Jim Hugunin.
• Another package Numarray was also developed, having some additional functionality.
• In 2005, Travis Oliphant created NumPy package by incorporating the features of
Numarray into Numeric package.
• There are many contributors to this open source project.
• NumPy is often used along with packages like SciPy (Scientific Python)
and Mat−plotlib (plotting library).
• This combination is widely used as a replacement for MatLab, a popular platform for
technical computing.
Operations using NumPy:
• Using NumPy, a developer can perform the following operations −
• Mathematical and logical operations on arrays.
• Fourier transforms and routines for shape manipulation.
• Operations related to linear algebra. NumPy has in-built functions for linear algebra and
random number generation.
Page 1 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
NumPy Environment:
• Standard Python distribution doesn't come bundled with NumPy module.
• A lightweight alternative is to install NumPy using popular Python package
installer, pip.
• If you have Python and PIP already installed on a system, then installation of NumPy is
very easy.
• Install it using this command: C:\Users\Your Name>pip install numpy
• If this command fails, then use a python distribution that already has NumPy installed
like, Anaconda, and Spyder etc.
• On the Windows operating system, The SciPy stack is provided by the Anaconda which
is a free distribution of the Python SciPy package.
• It can be downloaded from the official website: https://www.anaconda.com/.
• It is also available for Linux and Mac.
• The best way to enable NumPy is to use an installable binary package specific to your
operating system.
• These binaries contain full SciPy stack (inclusive of NumPy, SciPy, matplotlib,
IPython, SymPy and nose packages along with core Python).
Import NumPy
• Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
• Now NumPy is imported and ready to use.
Page 2 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example:
Example:
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
Output:
NumPy as np:
• NumPy is usually imported under the np alias.
• Alias: In Python alias are alternate names for referring to the same thing.
• Create an alias with the as keyword while importing:
import numpy as np
• Now the NumPy package can be referred to as np instead of numpy.
Example:
import numpy as np
arr = np.array ([1, 2, 3, 4, 5])
print(arr)
Output:
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).
• The basic ndarray is created using an array function in NumPy as follows −numpy.array
• Elements in Numpy arrays are accessed by using square brackets and can be initialized
by using nested Python Lists.
• We can create a NumPy Ndarray object by using the array () function.
numpy.array(object, dtype = None, copy = True, order = None, subok = False,
ndmin = 0)
• The above constructor takes the following parameters :
Page 3 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
• 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:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Page 4 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
2. import numpy as np
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype)
Output:
Page 5 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example: Change data type from float to integer by using 'i' as parameter value
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
Output:
Example: Change data type from float to integer by using int as parameter value
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
Output:
1-D Arrays:
• An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
Page 6 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
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)
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)
• The following examples show how to use the built-in range () function to return a list
object.
Example:
# create list object using range function
import numpy as np
list = range(5)
print list
Output:
[0, 1, 2, 3, 4]
• Python has a set of built-in methods that you can use on lists/arrays.
Page 7 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Page 8 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Page 9 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Page 10 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5 6 7]
Output:
<class 'numpy.ndarray'>
[list([1, 2, 3, 4, 5, 6, 7]) list([8, 9])]
2. numpy.frombuffer
• This function is used to create an array by using the specified buffer.
Syntax:
numpy.frombuffer (buffer, dtype = float, count = -1, offset = 0)
Example:
import numpy as np
l = b'hello world'
print(type(l))
a = np.frombuffer(l, dtype = "S1")
print(a)
print(type(a))
Output:
<class 'bytes'>
[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
<class 'numpy.ndarray'>
3. numpy.fromiter
• This routine is used to create a ndarray by using an iterable object.
• It returns a one-dimensional ndarray object.
Syntax:
numpy.fromiter(iterable, dtype, count = - 1)
Page 11 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example
import numpy as np
list = [0,2,4,6]
it = iter(list)
x = np.fromiter(it, dtype = float)
print(x)
print(type(x))
Output:
[0. 2. 4. 6.]
<class 'numpy.ndarray'>
1. Numpy.arange:
• It creates an array by using the evenly spaced values over the given interval.
Syntax:
numpy.arrange(start, stop, step, dtype)
Example:
import numpy as np
arr = np.arange(0,10,2,float)
print(arr)
Output:
[0. 2. 4. 6. 8.]
Example
import numpy as np
arr = np.arange(10,100,5,int)
print("The array over the given range is ",arr)
Output:
The array over the given range is [10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]
2. NumPy.linspace:
Page 12 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
• It is similar to the arrange function. However, it doesn’t allow us to specify the step size
in the syntax.
• Instead of that, it only returns evenly separated values over a specified period. The
system implicitly calculates the step size.
Syntax:
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
Example:
import numpy as np
arr = np.linspace(10, 20, 5)
print("The array over the given range is ",arr)
Output:
The array over the given range is [10. 12.5 15. 17.5 20.]
Example:
import numpy as np
arr = np.linspace(10, 20, 5, endpoint = False)
print("The array over the given range is ",arr)
Output:
The array over the given range is [10. 12. 14. 16. 18.]
Page 13 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
3. numpy.logspace:
• It creates an array by using the numbers that are evenly separated on a log scale.
Syntax:
numpy.logspace(start, stop, num, endpoint, base, dtype)
Example:
import numpy as np
arr = np.logspace(10, 20, num = 5, endpoint = True)
print("The array over the given range is ",arr)
Output:
The array over the given range is [1.00000000e+10 3.16227766e+12 1.00000000e+15
3.16227766e+171.00000000e+20]
Example:
import numpy as np
arr = np.logspace(10, 20, num = 5,base = 2, endpoint = True)
print("The array over the given range is ",arr)
Output:
The array over the given range is [1.02400000e+03 5.79261875e+03 3.27680000e+04
1.85363800e+05 1.04857600e+06]
NumPy Broadcasting:
• In Mathematical operations, we may need to consider the arrays of different shapes.
• NumPy can perform such operations where the array of different shapes is involved.
• For example, if we consider the matrix multiplication operation, if the shape of the two
matrices is the same then this operation will be easily performed.
• However, we may also need to operate if the shape is not similar.
Broadcasting Rules:
• Broadcasting is possible if the following cases are satisfied.
1. The smaller dimension array can be appended with '1' in its shape.
2. Size of each output dimension is the maximum of the input sizes in the dimension.
3. An input can be used in the calculation if its size in a particular dimension matches the
output size or its value is exactly 1.
Page 14 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
4. If the input size is 1, then the first data entry is used for the calculation along the
dimension.
• Broadcasting can be applied to the arrays if the following rules are satisfied.
1. All the input arrays have the same shape.
2. Arrays have the same number of dimensions, and the length of each dimension is either
a common length or 1.
3. Array with the fewer dimension can be appended with '1' in its shape.
Page 15 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example:
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
b = np.array([2,4,6,8])
print("\nprinting array a..")
print(a)
print("\nprinting array b..")
print(b)
print("\nAdding arrays a and b ..")
c = a + b;
print(c)
Output:
printing array a..
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Example:
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing array:")
print(a);
Page 16 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Printing array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Iterating over the array:
1 2 3 4 2 4 5 6 10 20 39 3
• Let's iterate over the transpose of the array given in the above example.
Example:
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing the array:")
print(a)
print("Printing the transpose of the array:")
at = a.T
print(at)
#this will be same as previous
for x in np.nditer(at):
print(print("Iterating over the array:"))
for x in np.nditer(a):
print(x,end=' ')
Output:
Printing the array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Printing the transpose of the array:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
1 2 3 4 2 4 5 6 10 20 39 3
Order of Iteration:
• As we know, there are two ways of storing values into the numpy arrays:
1. F-style order
2. C-style order
• Let's see an example of how the numpy Iterator treats the specific orders (F or C).
Example:
import numpy as np
Page 17 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the array:\n")
print(a)
print("\nPrinting the transpose of the array:\n")
at = a.T
print(at)
print("\nIterating over the transposed array\n")
for x in np.nditer(at):
print(x, end= ' ')
print("\nSorting the transposed array in C-style:\n")
c = at.copy(order = 'C')
print(c)
print("\nIterating over the C-style array:\n")
for x in np.nditer(c):
print(x,end=' ')
d = at.copy(order = 'F')
print(d)
print("Iterating over the F-style array:\n")
for x in np.nditer(d):
print(x,end=' ')
Output:
Printing the array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
[[ 1 2 10]
[2 4 20]
[3 5 39]
[4 6 3]]
1 2 3 4 2 4 5 6 10 20 39 3
[[ 1 2 10]
[2 4 20]
[3 5 39]
[4 6 3]]
1 2 10 2 4 20 3 5 39 4 6 3
Page 18 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
1 2 3 4 2 4 5 6 10 20 39 3
1. Bitwise_and Operation:
• The NumPy provides the bitwise_and () function which is used to calculate the
bitwise_and operation of the two operands.
• The bitwise and operation is performed on the corresponding bits of the binary
representation of the operands.
• If both the corresponding bit in the operands is set to 1, then only the resultant bit in the
AND result will be set to 1 otherwise it will be set to 0.
Example:
import numpy as np
a = 10
b = 12
print ("binary representation of a:",bin(a))
print ("binary representation of b:",bin(b))
print("Bitwise-and of a and b: ",np.bitwise_and(a,b))
Output:
binary representation of a: 0b1010
Page 19 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
A B AND (A, B)
0 0 0
0 1 0
1 0 0
1 1 1
2. Bitwise_or Operator:
• The NumPy provides the bitwise_or () function which is used to calculate the bitwise or
operation of the two operands.
• The bitwise or operation is performed on the corresponding bits of the binary
representation of the operands.
• If one of the corresponding bit in the operands is set to 1 then the resultant bit in the OR
result will be set to 1; otherwise it will be set to 0.
Example:
import numpy as np
a = 50
b = 90
print ("binary representation of a:",bin(a))
print ("binary representation of b:",bin(b))
print ("Bitwise-or of a and b: ",np.bitwise_or(a,b))
Output:
binary representation of a: 0b110010
binary representation of b: 0b1011010
Bitwise-or of a and b: 122
Or Truth Table:
• The output of the OR result of the two bits is 1 if one of the bits are 1 otherwise it will
be 0.
A B Or (A, B)
0 0 0
0 1 1
Page 20 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
1 0 1
1 1 1
3. Invert operation:
• It is used to calculate the bitwise not the operation of the given operand.
• The 2's complement is returned if the signed integer is passed in the function.
Example:
import numpy as np
arr = np.array([20],dtype = np.uint8)
print("Binary representation:",np.binary_repr(20,8))
print(np.invert(arr))
print("Binary representation: ", np.binary_repr(235,8))
Output:
Binary representation: 00010100
[235]
Binary representation: 11101011
Example:
import numpy as np
print("left shift of 20 by 3 bits",np.left_shift(20, 3))
print("Binary representation of 20 in 8 bits",np.binary_repr(20, 8))
print("Binary representation of 160 in 8 bits",np.binary_repr(160,8))
Output:
left shift of 20 by 3 bits 160
Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000
Example:
import numpy as np
print("Right shift of 20 by 3 bits",np.right_shift(20, 3))
Page 21 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Right shift of 20 by 3 bits 2
Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000
Page 22 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Page 23 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
• Numpy contains the trigonometric functions which are used to calculate the sine,
cosine, and tangent of the different angles in radian.
• The sin, cos, and tan functions return the trigonometric ratio for the specified angles.
• arcsin(), arccos(), and arctan() functions return the trigonometric inverse of the
specified angles.
• The numpy.degrees() function can be used to verify the result of these trigonometric
functions.
Page 24 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
wise. print(np.arccos(arr*np.pi/180))
np.arctan() It performs trigonometric import numpy as np
inverse of tangent arr=np.array([1,2,3])
element-wise. print(np.arctan(arr*np.pi/180))
2. Rounding Functions:
• The numpy provides various functions that can be used to truncate the value of a
decimal float number rounded to a particular precision of decimal numbers.
1. numpy.around() function:
• This function returns a decimal value rounded to a desired position of the decimal.
Syntax:
numpy.around(num, decimal)
Example:
import numpy as np
arr = np.array([12.202, 90.23120, 123.020, 23.202])
print("Printing the original array values:",end = " ")
print(arr)
print("Array values rounded off to 2 decimal position",np.around(arr, 2))
print("Array values rounded off to -1 decimal position",np.around(arr, -1))
Output:
Printing the original array values: [12.202 90.2312 123.02 23.202 ]
Array values rounded off to 2 decimal position [12.2 90.23 123.02 23.2 ]
Page 25 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Array values rounded off to -2 decimal position [10. 90. 120. 20.]
2. numpy.floor() function:
• This function is used to return the floor value of the input data which is the largest
integer not greater than the input value.
Example:
import numpy as np
arr = np.array([12.202, 90.23120, 123.020, 23.202])
print(np.floor(arr))
Output:
[ 12. 90. 123. 23.]
3. numpy.ceil() function:
• This function is used to return the ceiling value of the array values which is the smallest
integer value greater than the array element.
Example:
import numpy as np
arr = np.array([12.202, 90.23120, 123.020, 23.202])
print(np.ceil(arr))
Output:
[ 13. 91. 124. 24.]
Example:
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
print 'Our array is:'
print a
print '\n'
Page 26 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]
2. numpy.ptp():
• The name of the function numpy.ptp() is derived from the name peak-to-peak. It is used
to return the range of values along an axis.
• numpy.ptp()functions use to plays an important role in statistics by finding out Range of
given numbers.
• Range = max value – min value
Syntax:
ndarray.ptp(axis=None, out=None)
Page 27 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example 1:
import numpy as np
# 1D array
arr = [1, 2, 7, 20, np.nan]
print("arr : ", arr)
print("Range of arr : ", np.ptp(arr))
#1D array
arr = [1, 2, 7, 10, 16]
print("arr : ", arr)
print("Range of arr : ", np.ptp(arr))
Output:
arr : [1, 2, 7, 20, nan]
Range of arr : nan
arr : [1, 2, 7, 10, 16]
Range of arr : 15
Example 2:
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
Page 28 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]
3. numpy.percentile():
• Percentile (or a centile) is a measure used in statistics indicating the value below which
a given percentage of observations in a group of observations fall.
• numpy.percentile()function used to compute the nth percentile of the given data (array
elements) along the specified axis.
• The function numpy.percentile() takes the following arguments.
Syntax:
numpy.percentile(input, q, axis)
Example:
import numpy as np
a = np.array([[30,40,70],[80,20,10],[50,90,60]])
Page 29 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Our array is:
[[30 40 70]
[80 20 10]
[50 90 60]]
4. numpy.median():
• Median is defined as the value that is used to separate the higher range of data sample
with a lower range of data sample.
• Median is defined as the value separating the higher half of a data sample from the
lower half.
• The function numpy.median() is used to calculate the median of the multi-dimensional
or one-dimensional arrays.
• How to calculate median?
1. Given data points.
2. Arrange them in ascending order
3. Median = middle term if total no. of terms are odd.
4. Median = Average of the terms in the middle (if total no. of terms are even)
Syntax:
numpy.median(arr, axis = None)
Page 30 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example 1:
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:
import numpy as np
a = np.array([[30,65,70],[80,95,10],[50,90,60]])
Page 31 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Our array is:
[[30 65 70]
[80 95 10]
[50 90 60]]
5. numpy.mean():
• The mean can be calculated by adding all the items of the arrays dividing by the number
of array elements.
• We can also mention the axis along which the mean can be calculated.
• Arithmetic mean is the sum of elements along an axis divided by the number of
elements.
• The numpy.mean() function returns the arithmetic mean of elements in the array.
• If the axis is mentioned, it is calculated along it.
Example:
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
Page 32 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Our array is:
[[1 2 3]
[3 4 5]
[4 5 6]]
6. numpy.average():
• The numpy.average() function is used to find the weighted average along the axis of the
multi-dimensional arrays where their weights are given in another array.
• Weighted average is an average resulting from the multiplication of each component by
a factor reflecting its importance.
• The numpy.average() function computes the weighted average of elements in an array
according to their respective weight given in another array.
• The function can have an axis parameter.
• If the axis is not specified, the array is flattened.
• Considering an array [1,2,3,4] and corresponding weights [4,3,2,1], the weighted
average is calculated by adding the product of the corresponding elements and dividing
the sum by the sum of weights.
• Weighted average = (1*4+2*3+3*2+4*1)/(4+3+2+1)
Example 1:
import numpy as np
a = np.array([1,2,3,4])
Page 33 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Our array is:
[1 2 3 4]
Sum of weights
(2.0, 10.0)
Example 2:
import numpy as np
a = np.arange(6).reshape(3,2)
Page 34 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Our array is:
[[0 1]
[2 3]
[4 5]]
Modified array:
[ 0.625 2.625 4.625]
Modified array:
(array([ 0.625, 2.625, 4.625]), array([ 8., 8., 8.]))
7. Standard Deviation:
• Standard deviation is the square root of the average of squared deviations from mean.
• The formula for standard deviation is as follows:
std = sqrt(mean(abs(x - x.mean())**2))
• If the array is [1, 2, 3, 4], then its mean is 2.5.
• Hence the squared deviations are [2.25, 0.25, 0.25, 2.25] and the square root of its mean
divided by 4, i.e., sqrt (5/4) is 1.1180339887498949.
Example:
import numpy as np
print np.std([1,2,3,4])
Output:
1.1180339887498949
8. Variance:
• Variance is the average of squared deviations, i.e., mean(abs(x - x.mean())**2).
• In other words, the standard deviation is the square root of variance.
Example:
import numpy as np
print np.var([1,2,3,4])
Output:
1.25
Page 35 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example:
import numpy as np
a = np.array([[10,2,3],[4,5,6],[7,8,9]])
print("Sorting along the columns:")
print(np.sort(a))
print("Sorting along the rows:")
print(np.sort(a, 0))
data_type = np.dtype([('name', 'S10'),('marks',int)])
arr = np.array([('Mukesh',200),('John',251)],dtype = data_type)
print("Sorting data ordered by name")
print(np.sort(arr,order = 'name'))
Page 36 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
Sorting along the columns:
[[ 2 3 10]
[ 4 5 6]
[ 7 8 9]]
Sorting along the rows:
[[ 4 2 3]
[ 7 5 6]
[10 8 9]]
Sorting data ordered by name
[(b'John', 251) (b'Mukesh', 200)]
1. numpy.argsort() function:
• This function is used to perform an indirect sort on an input array that is, it returns an
array of indices of data which is used to construct the array of sorted data.
Example:
import numpy as np
a = np.array([90, 29, 89, 12])
print("Original array:\n",a)
sort_ind = np.argsort(a)
print("Printing indices of sorted data\n",sort_ind)
sort_a = a[sort_ind]
print("printing sorted array")
for i in sort_ind:
print(a[i],end = " ")
Output:
Original array:
[90 29 89 12]
Printing indices of sorted data
[3 1 2 0]
printing sorted array
12 29 89 90
2. numpy.lexsort() function:
• This function is used to sort the array using the sequence of keys indirectly.
• This function performs similarly to the numpy.argsort() which returns the array of
indices of sorted data.
Example:
import numpy as np
a = np.array(['a','b','c','d','e'])
Page 37 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
printing indices of sorted data
[0 3 1 4 2]
using the indices to sort the array
a 12
d 12
b 90
e 211
c 380
3. numpy.nonzero() function:
• This function is used to find the location of the non-zero elements from the array.
Example:
import numpy as np
b = np.array([12, 90, 380, 12, 211])
print("printing original array",b)
print("printing location of the non-zero elements")
print(b.nonzero())
Output:
printing original array [ 12 90 380 12 211]
printing location of the non-zero elements
(array([0, 1, 2, 3, 4]))
4. numpy.where() function:
• This function is used to return the indices of all the elements which satisfies a particular
condition.
Example:
import numpy as np
b = np.array([12, 90, 380, 12, 211])
print(np.where(b>12))
c = np.array([[20, 24],[21, 23]])
print(np.where(c>20))
Page 38 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
(array([1, 2, 4], dtype=int64),)
(array([0, 1, 1], dtype=int64), array([1, 0, 1], dtype=int64))
1. Array Assignment:
• The assignment of a numpy array to another array doesn't make the direct copy of the
original array, instead, it makes another array with the same content and same id.
• It represents the reference to the original array.
• Changes made on this reference are also reflected in the original array.
• The id() function returns the universal identifier of the array similar to the pointer in C.
Example:
import numpy as np
a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
print("Original Array:\n",a)
print("\nID of array a:",id(a))
b=a
print("\nmaking copy of the array a")
print("\nID of b:",id(b))
b.shape = 4,3;
print("\nChanges on b also reflect to a:")
print(a)
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
ID of array a: 139663602288640
making copy of the array a
ID of b: 139663602288640
Changes on b also reflect to a:
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
Page 39 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
2. ndarray.view() method:
• The ndarray. View () method returns the new array object which contains the same
content as the original array does.
• Since it is a new array object, changes made on this object do not reflect the original
array.
Example:
import numpy as np
a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
print("Original Array:\n",a)
print("\nID of array a:",id(a))
b = a.view()
print("\nID of b:",id(b))
print("\nprinting the view b")
print(b)
b.shape = 4,3;
print("\nChanges made to the view b do not reflect a")
print("\nOriginal array \n",a)
print("\nview\n",b)
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
ID of array a: 140280414447456
ID of b: 140280287000656
printing the view b
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
Changes made to the view b do not reflect a
Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
View
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
Page 40 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
3. ndarray.copy() method:
• It returns the deep copy of the original array which doesn't share any memory with the
original array.
• The modification made to the deep copy of the original array doesn't reflect the original
array.
Example:
import numpy as np
a = np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
print("Original Array:\n",a)
print("\nID of array a:",id(a))
b = a.copy()
print("\nID of b:",id(b))
print("\nprinting the deep copy b")
print(b)
b.shape = 4,3;
print("\nChanges made to the copy b do not reflect a")
print("\nOriginal array \n",a)
print("\nCopy\n",b)
Output:
Original Array:
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
ID of array a: 139895697586176
ID of b: 139895570139296
printing the deep copy b
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
Changes made to the copy b do not reflect a
Original array
[[ 1 2 3 4]
[ 9 0 2 3]
[ 1 2 3 19]]
Copy
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
Page 41 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
1. numpy.matlib.empty() function:
• This function is used to return a new matrix with the uninitialized entries.
• The syntax to use this function is given below.
numpy.matlib.empty(shape, dtype, order)
• It accepts the following parameter.
1. shape: It is the tuple defining the shape of the matrix.
2. dtype: It is the data type of the matrix.
3. order: It is the insertion order of the matrix, i.e. C or F.
Example:
import numpy as np
import numpy.matlib
print(numpy.matlib.empty((3,3)))
Output:
[[6.90262230e-310 6.90262230e-310 6.90262304e-310]
[6.90262304e-310 6.90261674e-310 6.90261552e-310]
[6.90261326e-310 6.90262311e-310 3.95252517e-322]]
2. Numpy.matlib.zeros () function:
• This function is used to create the matrix where the entries are initialized to zero.
Example:
import numpy as np
import numpy.matlib
print(numpy.matlib.zeros((4,3)))
Output:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
3. numpy.matlib.ones() function:
• This function returns a matrix with all the elements initialized to 1.
Example:
import numpy as np
import numpy.matlib
print(numpy.matlib.ones((2,2)))
Page 42 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
[[1. 1.]
[1. 1.]]
4. numpy.matlib.eye() function:
• This function returns a matrix with the diagonal elements initialized to 1 and zero
elsewhere.
• The syntax to use this function is given below.
numpy.matlib.eye(n, m, k, dtype)
• It accepts the following parameters.
1. n: It represents the number of rows in the resulting matrix.
2. m: It represents the number of columns, defaults to n.
3. k: It is the index of diagonal.
4. dtype: It is the data type of the output
Example:
import numpy as np
import numpy.matlib
print(numpy.matlib.eye(n = 3, M = 3, k = 0, dtype = int))
Output:
[[1 0 0]
[0 1 0]
[0 0 1]]
5. numpy.matlib.identity() function:
• This function is used to return an identity matrix of the given size.
• An identity matrix is the one with diagonal elements initializes to 1 and all other
elements to zero.
Example:
import numpy as np
import numpy.matlib
print(numpy.matlib.identity(5, dtype = int))
Output:
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]]
6. numpy.matlib.rand() function:
• This function is used to generate a matrix where all the entries are initialized with
random values.
Page 43 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Example:
import numpy as np
import numpy.matlib
print(numpy.matlib.rand(3,3))
Output:
[[0.86201511 0.86980769 0.06704884]
[0.80531086 0.53814098 0.84394673]
[0.85653048 0.8146121 0.35744405]]
SN Function Definition
1 dot() It is used to calculate the dot product of two arrays.
2 vdot() It is used to calculate the dot product of two vectors.
3 inner() It is used to calculate the inner product of two arrays.
4 matmul() It is used to calculate the matrix multiplication of two arrays.
5 det() It is used to calculate the determinant of a matrix.
6 solve() It is used to solve the linear matrix equation.
7 inv() It is used to calculate the multiplicative inverse of the matrix.
1. numpy.dot() function:
• This function is used to return the dot product of the two matrices.
• It is similar to the matrix multiplication.
Example:
import numpy as np
a = np.array([[100,200],[23,12]])
b = np.array([[10,20],[12,21]])
dot = np.dot(a,b)
print(dot)
Output:
[[3400 6200]
[ 374 712]]
The dot product is calculated as:
[100 * 10 + 200 * 12, 100 * 20 + 200 * 21] [23*10+12*12, 23*20 + 12*21]
2. numpy.vdot() function:
This function is used to calculate the dot product of two vectors.
It can be defined as the sum of the product of corresponding elements of multi-dimensional
arrays.
Example:
import numpy as np
a = np.array([[100,200],[23,12]])
Page 44 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
b = np.array([[10,20],[12,21]])
vdot = np.vdot(a,b)
print(vdot)
Page 45 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
Output:
5528
3. numpy.inner() function:
This function returns the sum of the product of inner elements of the one-dimensional array.
For n-dimensional arrays, it returns the sum of the product of elements over the last axis.
Example:
import numpy as np
a = np.array([1,2,3,4,5,6])
b = np.array([23,23,12,2,1,2])
inner = np.inner(a,b)
print(inner)
Output:
130
4. numpy.matmul() function:
It is used to return the multiplication of the two matrices.
It gives an error if the shape of both matrices is not aligned for multiplication.
Example:
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([[23,23,12],[2,1,2],[7,8,9]])
mul = np.matmul(a,b)
print(mul)
Output:
[[ 48 49 43]
[144 145 112]
[240 241 181]]
5. numpy determinant:
The determinant of the matrix can be calculated using the diagonal elements. The determinant
of following 2 X 2 matrix
A B
C D
can be calculated as AD - BC.
The numpy.linalg.det() function is used to calculate the determinant of the matrix.
Example:
import numpy as np
a = np.array([[1,2],[3,4]])
print(np.linalg.det(a))
Output:
Page 46 of 47
Subject: ADVANCE PYTHON Chapter - 2 B.C.A. Sem - 6
-2.0000000000000004
6. numpy.linalg.solve() function:
This function is used to solve a quadratic equation where values can be given in the form of the
matrix.The following linear equations
3X + 2 Y + Z = 10
X+Y+Z=5
can be represented by using three matrices as:
3 2 1
1 1 1
X Y Z and 10 5.
The two matrices can be passed into the numpy.solve() function given as follows.
Example:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[1,2],[3,4]])
print(np.linalg.solve(a, b))
Output:
[[1. 0.]
[0. 1.]]
7. numpy.linalg.inv() function:
This function is used to calculate the multiplicative inverse of the input matrix.
Example:
import numpy as np
a = np.array([[1,2],[3,4]])
print("Original array:\n",a)
b = np.linalg.inv(a)
print("Inverse:\n",b)
Output:
Original array:
[[1 2]
[3 4]]
Inverse:
[[-2. 1. ]
[ 1.5 -0.5]]
Page 47 of 47