[go: up one dir, main page]

100% found this document useful (1 vote)
8 views97 pages

Advance Python Unit - 2

NumPy is a Python library for efficient computation and processing of multidimensional arrays, created in 2005 by Travis Oliphant. It offers powerful data structures, array-oriented computing, and various mathematical functions, making it essential for data science and scientific computing. NumPy must be installed separately and can be imported using the alias 'np' for ease of use.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
8 views97 pages

Advance Python Unit - 2

NumPy is a Python library for efficient computation and processing of multidimensional arrays, created in 2005 by Travis Oliphant. It offers powerful data structures, array-oriented computing, and various mathematical functions, making it essential for data science and scientific computing. NumPy must be installed separately and can be imported using the alias 'np' for ease of use.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Python Numpy

JKM BCA College


 NumPy stands for Numeric Python which is a python package for
the computation and processing of the multidimensional and
single dimensional array elements.
 NumPy was created in 2005 by Travis Oliphant. It is an open
source project and you can use it freely.
 Using NumPy, mathematical and logical operations on arrays can
be performed.
 NumPy provides various powerful data structures, implementing
multi-dimensional arrays and matrices. These data structures are
used for the optimal computations regarding arrays and
matrices.
 NumPy is an open source library available in Python that aids in
mathematical, scientific, engineering, and data science
programming.
 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++.

JKM BCA College


 In Python we have lists that serve the purpose
of arrays, but they are slow to process.
 NumPy aims to provide an array object that is
up to 50x faster than traditional Python lists.
 The array object in NumPy is called ndarray, it
provides a lot of supporting functions that
make working with ndarray very easy.
 Arrays are very frequently used in data
science, where speed and resources are very
important.

JKM BCA College


 NumPy provides a convenient and efficient way to
handle the vast amount of data. NumPy is also
very convenient with Matrix multiplication and
data reshaping. NumPy is fast which makes it
reasonable to work with a large set of data.
 There are the following advantages of using
NumPy for data analysis.
◦ NumPy performs array-oriented computing.
◦ It efficiently implements the multidimensional arrays.
◦ It performs scientific computations.
◦ It is capable of performing Fourier Transform and
reshaping the data stored in multidimensional arrays.
◦ NumPy provides the in-built functions for linear algebra
and random number generation.

JKM BCA College


 NumPy doesn't come bundled with Python. We have to install it using the
python pip installer. Execute the following command.
◦ pip install numpy
 If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.
 It is best practice to install NumPy with the full SciPy stack. The binary
distribution of the SciPy stack is specific to the operating systems.
 Windows
 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/.
You can install NumPy using Anaconda:
◦ conda install -c anaconda numpy
 The CanoPy also comes with the full SciPy stack which is available as free as
well as commercial license. We can download it by visiting the link:
https://www.enthought.com/products/canopy/
 The Python (x, y) is also available free with the full SciPy distribution.
Download it by visiting the link: https://python-xy.github.io/

JKM BCA College


 Once NumPy is installed, import it in your applications by adding
the import keyword:
◦ import numpy
◦ Example
 import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
 NumPy is usually imported under the np alias. (alias: In Python
alias are an alternate name 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)
 To check your installed version of Numpy use the command
◦ print(np.__version__)

JKM BCA College


 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.
 The ndarray object can be created by using the array
routine of the numpy module. For this purpose, we
need to import the numpy.
 The basic ndarray is created using an array function
in NumPy as follows −
◦ numpy.array
 We can also pass a collection object into the array
routine to create the equivalent n-dimensional array.
The syntax is given below.
◦ >>> numpy.array(object, dtype = None, copy = True, order
= None, subok = False, ndmin = 0)

JKM BCA College


 The parameters are described in the following
table.
SN Parameter Description
1 object It represents the collection object. It can be a list, tuple, dictionary, set,
etc.
2 dtype We can change the data type of the array elements by changing this
option to the specified type. The default is none.
3 copy It is optional. By default, it is true which means the object is copied.

4 order There can be 3 possible values assigned to this option. It can be C


(column order), R (row order), or A (any)

5 subok The returned array will be base class array by default. We can change
this to make the subclasses passes through by setting this option to
true.
6 ndmin It represents the minimum dimensions of the resultant array.

JKM BCA College


 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)
 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)
 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)

JKM BCA College


 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)
 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)

JKM BCA College


 The NumPy provides a higher range of numeric data types than that provided by the
Python. A list of numeric data types is given in the following table.

SN Data type Description


1 bool_ It represents the boolean value indicating true or false. It is
stored as a byte.
2 int_ It is the default type of integer. It is identical to long type in C
that contains 64 bit or 32-bit integer.
3 intc It is similar to the C integer (c int) as it represents 32 or 64-bit
int.
4 intp It represents the integers which are used for indexing.
5 int8 It is the 8-bit integer identical to a byte. The range of the value is
-128 to 127.
6 int16 It is the 2-byte (16-bit) integer. The range is -32768 to 32767.
7 int32 It is the 4-byte (32-bit) integer. The range is -2147483648 to
2147483647.
8 int64 It is the 8-byte (64-bit) integer. The range is -
9223372036854775808 to 9223372036854775807.
9 uint8 It is the 1-byte (8-bit) unsigned integer.

JKM BCA College


10 uint16 It is the 2-byte (16-bit) unsigned integer.
11 uint32 It is the 4-byte (32-bit) unsigned integer.
12 uint64 It is the 8 bytes (64-bit) unsigned integer.
13 float_ It is identical to float64.
14 float16 It is the half-precision float. 5 bits are reserved for the
exponent. 10 bits are reserved for mantissa, and 1 bit is
reserved for the sign.
15 float32 It is a single precision float. 8 bits are reserved for the
exponent, 23 bits are reserved for mantissa, and 1 bit is
reserved for the sign.
16 float64 It is the double precision float. 11 bits are reserved for the
exponent, 52 bits are reserved for mantissa, 1 bit is used
for the sign.
17 complex_ It is identical to complex128.
18 complex64 It is used to represent the complex number where real and
imaginary part shares 32 bits each.
19 complex128 It is used to represent the complex number where real and
imaginary part shares 64 bits each.

JKM BCA College


 Below is a list of all data types in NumPy and the
characters used to represent them.
◦ i - integer
◦ b - boolean
◦ u - unsigned integer
◦ f - float
◦ c - complex float
◦ m - timedelta
◦ M - datetime
◦ O - object
◦ S - string
◦ U - unicode string
◦ V - fixed chunk of memory for other type ( void )

JKM BCA College


 Checking the Data Type of an Array
 The NumPy array object has a property
called dtype that returns the data type of the
array:
◦ Example: Get the data type of an array object:
 import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
◦ Example :Get the data type of an array containing
strings:
 import numpy as np
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype)

JKM BCA College


 Creating Arrays With a Defined Data Type
 We use the array() function to create arrays, this function can take an
optional argument: dtype that allows us to define the expected data
type of the array elements:
◦ Example: Create an array with data type string:
 import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
 For i, u, f, S and U we can define size as well.
◦ Example: Create an array with data type 4 bytes integer:
 import numpy as np
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)

JKM BCA College


 Arrays are used to store multiple values in one
single variable.Python does not have built-in
support for Arrays, but Python lists can be used.
 Example :
◦ arr = [1, 2, 3, 4, 5]
◦ arr1 = ["geeks", "for", "geeks"]

 # Python program to create


 # an array

 # Creating an array using list
 arr=[1, 2, 3, 4, 5]
 for i in arr:
 print(i)

JKM BCA College


 array(data type, value list) function is used to create an array
with data type and value list specified in its arguments.
Example :
◦ # Python code to demonstrate the working of
◦ # array()

◦ # importing "array" for array operations
◦ import array

◦ # initializing array with array values
◦ # initializes array with signed integers
◦ arr = array.array('i', [1, 2, 3])

◦ # printing original array
◦ print ("The new created array is : ",end="")
◦ for i in range (0,3):
◦ print (arr[i], end=" ")

◦ print ("\r")

JKM BCA College


 NumPy offers several functions to create arrays with initial placeholder content. These
minimize the necessity of growing arrays, an expensive operation. For
example: np.zeros,np.empty etc.
 Some methods for array creation in Numpy
FUNCTION DESCRIPTION
Return a new array of given shape and type, without
empty()
initializing entries
Return a new array with the same shape and type as a given
empty_like()
array
identity() Return the identity array
ones() Return a new array of given shape and type, filled with ones
Return an array of ones with the same shape and type as a
ones_like()
given array
zeros() Return a new array of given shape and type, filled with zeros
Return an array of zeros with the same shape and type as a
zeros_like()
given array
Return a full array with the same shape and type as a given
full_like()
array.
array() Create an array
asarray() Convert the input to an array
asmatrix() Interpret the input as a matrix
copy() Return an array copy of the given object
loadtxt() Load data from a text file
JKM BCA College
 It creates an uninitialized array of specified shape and dtype. It
uses the following constructor −
◦ numpy.empty(shape, dtype = float, order = 'C')
 The constructor takes the following parameters.
◦ shape :Shape of an empty array in int or tuple of int
◦ dtype: Desired output data type. Optional
◦ order: 'C' for C-style row-major array, 'F' for FORTRAN style column-major
array
 The following code shows an example of an empty array.
◦ import numpy as np
◦ x = np.empty([3,2], dtype = int)
◦ print x
 The output is as follows −
◦ [[22649312 1701344351]
◦ [1818321759 1885959276]
◦ [16779776 156368896]]
 Note − The elements in an array show random values as they are
not initialized.

JKM BCA College


 Returns a new array of specified size, filled with zeros.
◦ numpy.zeros(shape, dtype = float, order = 'C')
 The constructor takes the following parameters.
◦ shape:Shape of an empty array in int or sequence of int
◦ dtype: Desired output data type. Optional
◦ order: 'C' for C-style row-major array, 'F' for FORTRAN style column-major array
 Example 1
◦ # array of five zeros. Default dtype is float
◦ import numpy as np
◦ x = np.zeros(5)
◦ print x
 The output is as follows −
◦ [ 0. 0. 0. 0. 0.]
 Example 2
◦ import numpy as np
◦ x = np.zeros((5,), dtype = np.int)
◦ print x
 Now, the output would be as follows −
◦ [0 0 0 0 0]

JKM BCA College


 Returns a new array of specified size and type, filled with ones.
◦ numpy.ones(shape, dtype = None, order = 'C')
 The constructor takes the following parameters

shape: Shape of an empty array in int or tuple of int

dtype: Desired output data type. Optional

order: 'C' for C-style row-major array, 'F' for FORTRAN style column-major array

Example 1
◦ # array of five ones. Default dtype is float
◦ import numpy as np
◦ x = np.ones(5)
◦ print x
 The output is as follows −
◦ [ 1. 1. 1. 1. 1.]
 Example 2
◦ import numpy as np
◦ x = np.ones([2,2], dtype = int)
◦ print x
 Now, the output would be as follows −
◦ [[1 1] [1 1]]

JKM BCA College


 NumPy provides us the way to create an array by using the existing data.

 numpy.asarray
 This function is similar to numpy.array except for the fact that it has fewer
parameters. This routine is useful for converting Python sequence into ndarray.
◦ numpy.asarray(a, dtype = None, order = None)
 The constructor takes the following parameters.

a: Input data in any form such as list, list of tuples, tuples, tuple of tuples or tuple
of lists

dtype: By default, the data type of input data is applied to the resultant ndarray

order: C (row major) or F (column major). C is default
 Example 1
◦ # convert list to ndarray
◦ import numpy as np
◦ x = [1,2,3]
◦ a = np.asarray(x)
◦ print a
 Its output would be as follows −
◦ [1 2 3]

JKM BCA College


 Example 2  Example 4
◦ # dtype is set ◦ # ndarray from list of tuples
◦ import numpy as np ◦ import numpy as np
◦ x = [1,2,3] ◦ x = [(1,2,3),(4,5)]
◦ a = np.asarray(x, dtype = float) ◦ a = np.asarray(x)
◦ print a ◦ print a
 Now, the output would be as follows −  Here, the output would be as follows −
◦ [ 1. 2. 3.] ◦ [(1, 2, 3) (4, 5)]
 Example 3
◦ # ndarray from tuple
◦ import numpy as np
◦ x = (1,2,3)
◦ a = np.asarray(x)
◦ print a
 Its output would be −
◦ [1 2 3]

JKM BCA College


 This function interprets a buffer as one-dimensional array.
Any object that exposes the buffer interface is used as
parameter to return an ndarray.
◦ numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
 The constructor takes the following parameters.
◦ buffer: Any object that exposes buffer interface
◦ dtype: Data type of returned ndarray. Defaults to float
◦ count: The number of items to read, default -1 means all data
◦ offset: The starting position to read from. Default is 0
 Example
◦ import numpy as np
◦ s = 'Hello World'
◦ a = np.frombuffer(s, dtype = 'S1')
◦ print a
 Here is its output −
◦ ['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']

JKM BCA College


 This function builds an ndarray object from any iterable object. A
new one-dimensional array is returned by this function.
◦ numpy.fromiter(iterable, dtype, count = -1)
 Here, the constructor takes the following parameters.
◦ iterable: Any iterable object
◦ dtype: Data type of resultant array
◦ count: The number of items to be read from iterator. Default is -1 which
means all data to be read
 Example
◦ # obtain iterator object from list
◦ import numpy as np
◦ list = range(5)
◦ it = iter(list)
◦ # use iterator to create ndarray
◦ x = np.fromiter(it, dtype = float)
◦ print x
 Now, the output would be as follows −
◦ [0. 1. 2. 3. 4.]

JKM BCA College


 numpy.arange
 This function returns an ndarray object containing evenly spaced
values within a given range. The format of the function is as
follows −
◦ numpy.arange(start, stop, step, dtype)
 The constructor takes the following parameters.
◦ start: The start of an interval. If omitted, defaults to 0
◦ stop: The end of an interval (not including this number)
◦ step: Spacing between values, default is 1
◦ dtype: Data type of resulting ndarray. If not given, data type of input is
used
 Example 1
◦ import numpy as np
◦ x = np.arange(5)
◦ print x
 Its output would be as follows −
◦ [0 1 2 3 4]

JKM BCA College


 Example 2
◦ import numpy as np
◦ # dtype set
◦ x = np.arange(5, dtype = float)
◦ print x
 Here, the output would be −
◦ [0. 1. 2. 3. 4.]
 Example 3
◦ # start and stop parameters set
◦ import numpy as np
◦ x = np.arange(10,20,2)
◦ print x
 Its output is as follows −
◦ [10 12 14 16 18]

JKM BCA College


 This function is similar to arange() function. In this
function, instead of step size, the number of evenly
spaced values between the interval is specified. The
usage of this function is as follows −
◦ numpy.linspace(start, stop, num, endpoint, retstep, dtype)
 The constructor takes the following parameters.
◦ start: The starting value of the sequence
◦ stop: The end value of the sequence, included in the
sequence if endpoint set to true
◦ num: The number of evenly spaced samples to be
generated. Default is 50
◦ endpoint: True by default, hence the stop value is included
in the sequence. If false, it is not included
◦ retstep: If true, returns samples and step between the
consecutive numbers
◦ dtype: Data type of output ndarray

JKM BCA College


 Example 1  Example 3
◦ import numpy as np ◦ # find retstep value
◦ x = np.linspace(10,20,5) ◦ import numpy as np
◦ print x ◦ x = np.linspace(1,2,5, retstep = True)
◦ print x
 Its output would be −
◦ [10. 12.5 15. 17.5 20.] ◦ # retstep here is 0.25
 Example 2  Now, the output would be −
◦ # endpoint set to false ◦ (array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
◦ import numpy as np
◦ x = np.linspace(10,20, 5,
endpoint = False)
◦ print x
 The output would be −
◦ [10. 12. 14. 16. 18.]

JKM BCA College


 This function returns an ndarray object that contains
the numbers that are evenly spaced on a log scale.
Start and stop endpoints of the scale are indices of
the base, usually 10.
◦ numpy.logspace(start, stop, num, endpoint, base, dtype)
 Following parameters determine the output
of logspace function.
◦ start: The starting point of the sequence is base
◦ stop: The final value of sequence is base
◦ num: The number of values between the range. Default is
50
◦ endpoint: If true, stop is the last value in the range
◦ base: Base of log space, default is 10
◦ dtype: Data type of output array. If not given, it depends
upon other input arguments

JKM BCA College


 Example 1
◦ import numpy as np
◦ # default base is 10
◦ a = np.logspace(1.0, 2.0, num = 10)
◦ print a
 Its output would be as follows −
◦ [ 10. 12.91549665 16.68100537 21.5443469 27.82559402
35.93813664 46.41588834 59.94842503 77.42636827 100. ]
 Example 2
◦ # set base of log space to 2
◦ import numpy as np
◦ a = np.logspace(1,10,num = 10, base = 2)
◦ print a
 Now, the output would be −
◦ [ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]

JKM BCA College


 The term broadcasting refers to the ability of NumPy to
treat arrays of different shapes during arithmetic
operations. Arithmetic operations on arrays are usually
done on corresponding elements. If two arrays are of
exactly the same shape, then these operations are
smoothly performed.
 Example 1
◦ import numpy as np
◦ a = np.array([1,2,3,4])
◦ b = np.array([10,20,30,40])
◦ c=a*b
◦ print c
 Its output is as follows −
◦ [10 40 90 160]

JKM BCA College


 If the dimensions of two arrays are dissimilar, element-to-element
operations are not possible. However, operations on arrays of non-
similar shapes is still possible in NumPy, because of the broadcasting
capability. The smaller array is broadcast to the size of the larger array
so that they have compatible shapes.
 Broadcasting is possible if the following rules are satisfied −
◦ Array with smaller ndim than the other is prepended with '1' in its shape.
◦ Size in each dimension of the output shape is maximum of the input sizes in that
dimension.
◦ An input can be used in calculation, if its size in a particular dimension matches the
output size or its value is exactly 1.
◦ If an input has a dimension size of 1, the first data entry in that dimension is used for
all calculations along that dimension.
 A set of arrays is said to be broadcastable if the above rules produce a
valid result and one of the following is true −
◦ Arrays have exactly the same shape.
◦ Arrays have the same number of dimensions and the length of each dimension is
either a common length or 1.
◦ Array having too few dimensions can have its shape prepended with a dimension of
length 1, so that the above stated property is true.

JKM BCA College


 The following program shows an
example of broadcasting. ◦ The output of this program would
be as follows First array:
 Example 2
◦ [[ 0. 0. 0.]
◦ import numpy as np
◦ [ 10. 10. 10.]
◦ a=np.array([[0.0,0.0,0.0],[10.0,1
◦ [ 20. 20. 20.]
0.0,10.0],[20.0,20.0,20.0],[30.0
,30.0,30.0]]) ◦ [ 30. 30. 30.]]
◦ b = np.array([1.0,2.0,3.0])
◦ print 'First array:' ◦ Second array:
◦ print a ◦ [ 1. 2. 3.]
◦ print '\n'
◦ print 'Second array:' ◦ First Array + Second Array
◦ print b ◦ [[ 1. 2. 3.]
◦ print '\n' ◦ [ 11. 12. 13.]
◦ print 'First Array + Second ◦ [ 21. 22. 23.]
Array' ◦ [ 31. 32. 33.]]
◦ print a + b

JKM BCA College


 The following figure demonstrates how
array b is broadcast to become compatible
with a.

JKM BCA College


 NumPy package contains an iterator object numpy.nditer. It is an efficient
multidimensional iterator object using which it is possible to iterate over an array.
Each element of an array is visited using Python’s standard Iterator interface.
 Let us create a 3X4 array using arange() function and iterate over it using nditer.
 Example 1
◦ import numpy as np
◦ a = np.arange(0,60,5)
◦ a = a.reshape(3,4)
◦ print 'Original array is:'
◦ print a print '\n'
◦ print 'Modified array is:'
◦ for x in np.nditer(a):
 print x,T
 The output of this program is as follows −
◦ Original array is:
◦ [[ 0 5 10 15]
◦ [20 25 30 35]
◦ [40 45 50 55]]

◦ Modified array is:


◦ 0 5 10 15 20 25 30 35 40 45 50 55

JKM BCA College


 Example 2
 The order of iteration is chosen to match the memory layout of an array, without considering a
particular ordering. This can be seen by iterating over the transpose of the above array.
◦ import numpy as np
◦ a = np.arange(0,60,5)
◦ a = a.reshape(3,4)
◦ print 'Original array is:'
◦ print a
◦ print '\n'
◦ print 'Transpose of the original array is:'
◦ b = a.T
◦ print b
◦ print '\n'
◦ print 'Modified array is:'
◦ for x in np.nditer(b):
 print x,
 The output of the above program is as follows −
◦ Original array is:
◦ [[ 0 5 10 15]
◦ [20 25 30 35]
◦ [40 45 50 55]]
◦ Transpose of the original array is:
◦ [[ 0 20 40]
◦ [ 5 25 45]
◦ [10 30 50]
◦ [15 35 55]]
◦ Modified array is: 0 5 10 15 20 25 30 35 40 45 50 55

JKM BCA College


 There are times when it is important to visit the
elements of an array in a specific order, irrespective
of the layout of the elements in memory. The nditer
object provides an order parameter to control this
aspect of iteration. The default, having the behavior
described above, is order=’K’ to keep the existing
order. This can be overridden with order=’C’ for C
order and order=’F’ for Fortran order.
 Example:
◦ Python program for
◦ # iterating over array
◦ # using particular order  Output:
◦ import numpy as geek ◦ Original array is:
◦ # creating an array using arrange ◦ [[ 0 1 2 3]
[ 4 5 6 7]
◦ # method ◦
◦ [ 8 9 10 11]]
◦ a = geek.arange(12)
◦ Modified array in C-style order:
◦ # shape array with 3 rows and ◦ 0 1 2 3 4 5 6 7 8 9 10 11
◦ # 4 columns
◦ a = a.reshape(3,4)
◦ print('Original array is:')
◦ print(a)
◦ print()
◦ print('Modified array in C-style order:')
◦ # iterating an array in a given
◦ # order
◦ for x in geek.nditer(a, order = 'C'):
◦ print(x)

JKM BCA College


 The nditer object has another optional parameter  Output:
called op_flags. Its default value is read-only, but can be set to
◦ Original array is:
read-write or write-only mode. This will enable modifying
array elements using this iterator. ◦ [[ 0 1 2 3]
◦ # Python program for ◦ [ 4 5 6 7]
◦ # modifying array values ◦ [ 8 9 10 11]]
◦ import numpy as geek ◦ Modified array
is:
◦ # creating an array using arrange
◦ [[ 0 5 10 15]
◦ # method
◦ [20 25 30 35]
◦ a = geek.arange(12)
◦ [40 45 50 55]]
◦ # shape array with 3 rows and
◦ # 4 columns
◦ a = a.reshape(3,4)
◦ print('Original array is:')
◦ print(a)
◦ print()
◦ # modifying array values
◦ for x in geek.nditer(a, op_flags = ['readwrite']):
◦ x[...] = 5*x
◦ print('Modified array is:')
◦ print(a)

JKM BCA College


 The nditer class constructor has a flags parameter, which can take the
following values

PARAMETER DESCRIPTION

Causes values given to be one-dimensional


external_loop arrays with multiple values instead of zero-
dimensional array

c_index C_order index can be tracked

f_index Fortran_order index is tracked

Type of indexes with one per iteration can be


multi-index
tracked

JKM BCA College


# Python program for
# iterating array values
# using f_index
import numpy as geek  Output:
# creating an array using arrange ◦ Original array is:
◦ [[ 0 1 2]
# method
◦ [ 3 4 5]]
a = geek.arange(6) ◦ 0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5>
# shape array with 2 rows and
# 3 columns
a = a.reshape(2,3)
print('Original array is:')
print(a)
print()
# iterating array using f_index
# parameter
it = geek.nditer(a, flags=['f_index'])
while not it.finished:
print("%d <%d>" % (it[0], it.index),
end=" ")
it.iternext()

JKM BCA College


 If two arrays are broadcastable, a combined nditer object is able to
iterate upon them concurrently. Assuming that an array a has dimension
3X4, and there is another array b of dimension 1X4, the iterator of
following type is used (array b is broadcast to size of a).
◦ Python program for
◦ # iterating array

◦ import numpy as geek

◦ # creating an array using arrange
◦ # method
◦ a = geek.arange(12)

◦ # shape array with 3 rows and
◦ # 4 columns
◦ a = a.reshape(3,4)

◦ print('First array is:')
◦ print(a)
◦ print()

JKM BCA College


◦ Creating second array using
◦ # array method
◦ print('Second array is:')
◦ b = geek.array([5, 6, 7, 8], dtype = int)
◦ print(b)
◦ print()

◦ print('Modified array is:')
◦ for x,y in geek.nditer([a,b]):
◦ print("%d:%d" % (x,y))
 Output:
◦ First array is:
◦ [[ 0 1 2 3]
◦ [ 4 5 6 7]
◦ [ 8 9 10 11]]
◦ Second array is:
◦ [5 6 7 8]
◦ Modified array is:
◦ 0:5 1:6 2:7 3:8 4:5 5:6 6:7 7:8 8:5 9:6 10:7 11:8

JKM BCA College


 Numpy provides the following bitwise operators.

SN Operator Description
1 bitwise_and It is used to calculate the bitwise and operation between
the corresponding array elements.

2 bitwise_or It is used to calculate the bitwise or operation between the


corresponding array elements.

3 invert It is used to calculate the bitwise not the operation of the


array elements.

4 left_shift It is used to shift the bits of the binary representation of


the elements to the left.

5 right_shift It is used to shift the bits of the binary representation of


the elements to the right.

JKM BCA College


 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
binary representation of b: 0b1100
Bitwise-and of a and b: 8

JKM BCA College


 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

JKM BCA College


 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

JKM BCA College


 It shifts the bits in the binary representation of the
operand to the left by the specified position. An equal
number of 0s are appended from the right.
 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

JKM BCA College


 It shifts the bits in the binary representation of the
operand to the right by the specified position. An equal
number of 0s are appended from the left.
 Example
import numpy as np

print(“right shift of 20 by 3 bits",np.right_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:
right shift of 20 by 3 bits 2
Binary representation of 20 in 8 bits 00010100
Binary representation of 160 in 8 bits 10100000

JKM BCA College


 NumPy contains the various functions for the
operations on the arrays of dtype string.
 add()
 It is used to concatenate the corresponding array
ele
 numpy.char.add() method example
import numpy as np
print("Concatenating two string arrays:")
print(np.char.add(['welcome','Hi'], [' to Javatpoint', ' read p
ython'] ))
 Output:
Concatenating two string arrays:
['welcome to Javatpoint' 'Hi read python‘]

JKM BCA College


 It returns the multiple copies of the specified
string, i.e., if a string 'hello' is multiplied by 3
then, a string 'hello hello' is returned.
 numpy.char.multiply() method example
import numpy as np
print("Printing a string multiple times:")
print(np.char.multiply("hello ",3))
 Output:
Printing a string multiple times:
hello hello hello

JKM BCA College


 It returns the copy of the string where the
original string is centered with the left and right
padding filled with the specified number of fill
characters.
 numpy.char.center() method example
import numpy as np
print("Padding the string through left and right with the
fill char *");
#np.char.center(string, width, fillchar)
print(np.char.center("Javatpoint", 20, '*'))
 Output:
Padding the string through left and right with the fill char *
*****Javatpoint*****

JKM BCA College


 It returns a copy of the original string in
which the first letter of the original string is
converted to the Upper Case.
 numpy.char.capitalize() method example
import numpy as np
print("Capitalizing the string using capitalize()...")
print(np.char.capitalize("welcome to javatpoint"))
 Output:
Capitalizing the string using capitalize()...
Welcome to javatpoint

JKM BCA College


 It returns the title cased version of the string,
i.e., the first letter of each word of the string
is converted into the upper case.
 numpy.char.title() method example
import numpy as np
print("Converting string into title cased version...")
print(np.char.title("welcome to javatpoint"))
 Output:
Converting string into title cased version...
Welcome To Javatpoint

JKM BCA College


 It returns a copy of the string in which all the
letters are converted into the lower case.
 numpy.char.lower() method example
import numpy as np
print("Converting all the characters of the string into lowerc
ase...")
print(np.char.lower("WELCOME TO JAVATPOINT"))
 Output:
Converting all the characters of the string into lowercase...
welcome to javatpoint

JKM BCA College


 It returns a copy of the string in which all the
letters are converted into the upper case.
 numpy.char.upper() method example
import numpy as np
print("Converting all the characters of the string int
o uppercase...")
print(np.char.upper("Welcome To Javatpoint"))
 Output:
Converting all the characters of the string into uppercase...
WELCOME TO JAVATPOINT

JKM BCA College


 It returns a list of words in the string.
 numpy.char.split() method example
import numpy as np
print("Splitting the String word by word..")
print(np.char.split("Welcome To Javatpoint"),sep =
" ")
 Output:
Splitting the String word by word..
['Welcome', 'To', 'Javatpoint']

JKM BCA College


 It returns the list of lines in the string,
breaking at line boundaries.
 numpy.char.splitlines() method example
import numpy as np
print("Splitting the String line by line..")
print(np.char.splitlines("Welcome\nTo\nJavatpoint"))
 Output:
Splitting the String line by line..
['Welcome', 'To', 'Javatpoint']

JKM BCA College


 Returns a copy of the string with the leading and
trailing white spaces removed.
 numpy.char.strip() method example
import numpy as np
str = " welcome to javatpoint "
print("Original String:",str)
print("Removing the leading and trailing whitespaces fro
m the string")
print(np.char.strip(str))
 Output:
Original String: welcome to javatpoint
Removing the leading and trailing whitespaces from the string
welcome to javatpoint

JKM BCA College


 It returns a string which is the concatenation
of all the strings specified in the given
sequence.
 numpy.char.join() method example
import numpy as np
print(np.char.join(':','HM'))
 Output:
H:M

JKM BCA College


 It returns a copy of the string by replacing all
occurrences of a particular substring with the
specified one.
 numpy.char.replace() method example
import numpy as np
str = "Welcome to Javatpoint"
print("Original String:",str)
print("Modified String:",end=" ")
print(np.char.replace(str, "Welcome to","www."))
 Output:
Original String: Welcome to Javatpoint
Modified String: www. Javatpoint

JKM BCA College


 The math module is used to access mathematical functions in the
Python. All methods of this functions are used for integer or real
type objects, not for complex numbers.
 To use this module, we should import that module into our code.
◦ import math
 Some Constants
 These constants are used to put them into our calculations.
Sr.No. Constants & Description
1 Pi : Return the value of pi: 3.141592

2 E : Return the value of natural base e. e is 0.718282

3 Tau : Returns the value of tau. tau = 6.283185

4 Inf : Returns the infinite


5 Nan : Not a number type.

JKM BCA College


◦ import math
◦ # returning the value of const. pi
◦ print ("The value of const. pi is : ", end="")
◦ print (math.pi)

◦ # returning the value of const. e


◦ print ("The value of const. e is : ", end="")
◦ print (math.e)
 Output:
◦ The value of const. pi is : 3.141592653589793 The
value of const. e is : 2.718281828459045

JKM BCA College


 ceil() :- This function returns the smallest integral value greater
than the number. If number is already integer, same number is
returned.
 floor() :- This function returns the greatest integral value smaller
than the number. If number is already integer, same number is
returned.
◦ import math
◦ a = 2.3
◦ # returning the ceil of 2.3
◦ print ("The ceil of 2.3 is : ", end="")
◦ print (math.ceil(a))
◦ # returning the floor of 2.3
◦ print ("The floor of 2.3 is : ", end="")
◦ print (math.floor(a))
 Output:
◦ The ceil of 2.3 is : 3
◦ The floor of 2.3 is : 2

JKM BCA College


 fabs() :- This function returns the absolute value of the number.
 factorial() :- This function returns the factorial of the number. An
error message is displayed if number is not integral.
◦ import math
◦ a = -10
◦ b= 5
◦ # returning the absolute value.
◦ print ("The absolute value of -10 is : ", end="")
◦ print (math.fabs(a))
◦ # returning the factorial of 5
◦ print ("The factorial of 5 is : ", end="")
◦ print (math.factorial(b))
 Output:
◦ The absolute value of -10 is : 10.0
◦ The factorial of 5 is : 120

JKM BCA College


 copysign(a, b) :- This function returns the number with the value of ‘a’
but with the sign of ‘b’. The returned value is float type.
 gcd() :- This function is used to compute the greatest common divisor of
2 numbers mentioned in its arguments. This function works in python
3.5 and above.
◦ import math
◦ a = -10
◦ b = 5.5
◦ c = 15
◦ d=5
◦ # returning the copysigned value.
◦ print ("The copysigned value of -10 and 5.5 is : ", end="")
◦ print (math.copysign(5.5, -10))
◦ # returning the gcd of 15 and 5
◦ print ("The gcd of 5 and 15 is : ", end="")
◦ print (math.gcd(5,15))
 Output:
◦ The copysigned value of -10 and 5.5 is : -5.5
◦ The gcd of 5 and 15 is : 5

JKM BCA College


 exp(a) :- This function returns the value of e raised to
the power a (e**a) .
 log(a, b) :- This function returns the logarithmic value
of a with base b. If base is not mentioned, the
computed value is of natural log.
◦ import math
◦ # returning the exp of 4
◦ print ("The e**4 value is : ", end="")
◦ print (math.exp(4))
◦ # returning the log of 2,3
◦ print ("The value of log 2 with base 3 is : ", end="")
◦ print (math.log(2,3))
 Output:
◦ The e**4 value is : 54.598150033144236
◦ The value of log 2 with base 3 is : 0.6309297535714574

JKM BCA College


 pow(a, b) :- This function is used to compute value
of a raised to the power b (a**b).
 sqrt() :- This function returns the square root of the
number.
◦ import math
◦ # returning the value of 3**2
◦ print ("The value of 3 to the power 2 is : ", end="")
◦ print (math.pow(3,2))
◦ # returning the square root of 25
◦ print ("The value of square root of 25 : ", end="")
◦ print (math.sqrt(25))
 Output:
◦ The value of 3 to the power 2 is : 9.0
◦ The value of square root of 25 : 5.0

JKM BCA College


 Python has the ability to manipulate some
statistical data and calculate results of various
statistical operations using the file “statistics“,
useful in domain of mathematics.
 These functions calculate the average value from
a sample or population.
 mean() Arithmetic mean value (average) of data.
 harmonic_mean() Harmonic mean value of data.
 median() Median value (middle value) of data.
 median__low() Low median value of data.
 median__high() High median value of data.
 median__grouped() Median of the grouped data and also
calculate the 50th percentile of the grouped
data.
 mode() Maximum number of occurrence of data.

JKM BCA College


 mean() :- This function returns the mean or average of the data passed
in its arguments. If passed argument is empty, StatisticsError is raised.
 mode() :- This function returns the number with maximum number of
occurrences. If passed argument is empty, StatisticsError is raised.
◦ import statistics

◦ # initializing list
◦ li = [1, 2, 3, 3, 2, 2, 2, 1]

◦ # using mean() to calculate average of list elements


◦ print ("The average of list values is : ",end="")
◦ print (statistics.mean(li))

◦ # using mode() to print maximum occurring of list elements


◦ print ("The maximum occurring element is : ",end="")
◦ print (statistics.mode(li))
 Output:
◦ The average of list values is : 2.0
◦ The maximum occurring element is : 2

JKM BCA College


 median() :- This function is used to calculate the
median, i.e middle element of data. If passed
argument is empty, StatisticsError is raised.
 median_low() :- This function returns the median of
data in case of odd number of elements, but in case
of even number of elements, returns the lower of two
middle elements. If passed argument is
empty, StatisticsError is raised.
 median_high() :- This function returns the median of
data in case of odd number of elements, but in case
of even number of elements, returns the higher of
two middle elements. If passed argument is
empty, StatisticsError is raised.

JKM BCA College


◦ import statistics

◦ # initializing list
◦ li = [1, 2, 2, 3, 3, 3]

◦ # using median() to print median of list elements
◦ print ("The median of list element is : ",end="")
◦ print (statistics.median(li))

◦ # using median_low() to print low median of list elements
◦ print ("The lower median of list element is : ",end="")
◦ print (statistics.median_low(li))

◦ # using median_high() to print high median of list elements
◦ print ("The higher median of list element is : ",end="")
◦ print (statistics.median_high(li))
 Output:
◦ The median of list element is : 2.5
◦ The lower median of list element is : 2
◦ The higher median of list element is : 3

JKM BCA College


 This function is used to calculate median of
the groped data also calculate 50th percentile
of the grouped data
 Example
◦ list = [2,2,3,4]
◦ print ("The median_grouped values is : ",end="")
◦ print (statistics.median_grouped(list))
 Output
◦ The median_grouped values is : 2.5

JKM BCA College


 Sorting means putting elements in an ordered
sequence.
 Ordered sequence is any sequence that has an order
corresponding to elements, like numeric or
alphabetical, ascending or descending.
 The NumPy ndarray object has a function
called sort(), that will sort a specified array.
 Example
◦ import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))
 output
◦ [0 1 2 3]
 Note: This method returns a copy of the array,
leaving the original array unchanged.

JKM BCA College


 You can also sort arrays of strings, or any other data type
 Example
◦ import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))
 Output
◦ ['apple' 'banana' 'cherry']
 Sorting a 2-D Array
 If you use the sort() method on a 2-D array, both arrays will be
sorted:
 Example
◦ import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
 Output
◦ [[2 3 4]
◦ [0 1 5]]

JKM BCA College


 It has the following parameters
 numpy.sort(a, axis, kind, order)
Output :
arr : Array to be sorted.
axis : Axis along which we need array to be started. 
order : This argument specifies which fields to
compare first.
kind : [‘quicksort’{default}, ‘mergesort’, Along first axis :
‘heapsort’]Sorting algorithm.
 Example [[10 1] [12 15]]
import numpy as np
# sort along the first axis
Along first axis :
a = np.array([[12, 15], [10, 1]]) [[10 15] [ 1 12]]
arr1 = np.sort(a, axis = 0)
print ("Along first axis : \n", arr1) Along none axis :
# sort along the last axis [ 1 10 12 15]
a = np.array([[10, 15], [12, 1]])
arr2 = np.sort(a, axis = -1)
print ("\nAlong first axis : \n", arr2)
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = None)
print ("\nAlong none axis : \n", arr1)

JKM BCA College


 You can search an array for a certain value, and return the
indexes that get a match.
 To search an array, use the where() method.
 Example
 Find the indexes where the value is 4:
◦ import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)
 Output
◦ (array([3, 5, 6]),)
 The example above will return a tuple: (array([3, 5, 6],)
 Which means that the value 4 is present at index 3, 5, and 6.

JKM BCA College


 Example
 Find the indexes where the values are even:
◦ import numpy as np

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

x = np.where(arr%2 == 0)

print(x)
 output
◦ (array([1, 3, 5, 7]),)

JKM BCA College


 There is a method called searchsorted() which performs a binary search
in the array, and returns the index where the specified value would be
inserted to maintain the search order.
 The searchsorted() method is assumed to be used on sorted arrays.
 Example
 Find the indexes where the value 7 should be inserted:
◦ import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7)
print(x)
 Output
◦ 1
 The number 7 should be inserted on index 1 to remain the sort order.
 The method starts the search from the left and returns the first index
where the number 7 is no longer larger than the next value.

JKM BCA College


 By default the left most index is returned, but we can
give side='right' to return the right most index
instead.
 Example
 Find the indexes where the value 7 should be
inserted, starting from the right:
◦ import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7, side='right')
print(x)
 Output
◦ 2

JKM BCA College


 Multiple Values
 To search for more than one value, use an array with the
specified values.
 Example
 Find the indexes where the values 2, 4, and 6 should be inserted:
◦ import numpy as np
arr = np.array([1, 3, 5, 7])
x = np.searchsorted(arr, [2, 4, 6])
print(x)
 Output
◦ [1 2 3]
 The return value is an array: [1 2 3] containing the three indexes
where 2, 4, 6 would be inserted in the original array to maintain
the order.

JKM BCA College


 While working with NumPy, you might have
seen some functions return the copy whereas
some functions return the view. The main
difference between copy and view is that the
copy is the new array whereas the view is the
view of the original array. In other words, it
can be said that the copy is physically stored
at another location and view has the same
memory location as the original array.

JKM BCA College


 Simple assignments do not make the copy of array object. Instead, it uses the same id()
of the original array to access it. The id() returns a universal identifier of Python object,
similar to the pointer in C.
 Furthermore, any changes in either gets reflected in the other. For example, the
changing shape of one will change the shape of the other too.
 Example
◦ import numpy as np
◦ a = np.arange(6)
◦ print 'Our array is:'
◦ print a
◦ print 'Applying id() function:‘
◦ print id(a)
◦ print 'a is assigned to b:'
◦ b=a
◦ print b
◦ print 'b has same id():'
◦ print id(b)
◦ print 'Change shape of b:'
◦ b.shape = 3,2
◦ print b
◦ print 'Shape of a also gets changed:'
◦ print a
JKM BCA College
 It will produce the following output −
Our array is:
[0 1 2 3 4 5]
Applying id() function:
139747815479536
a is assigned to b:
[0 1 2 3 4 5]
b has same id():
139747815479536
Change shape of b:
[[0 1]
[2 3]
[4 5]]
Shape of a also gets changed:
[[0 1]
[2 3]
[4 5]]

JKM BCA College


 This is also known as Shallow Copy. The view is just a view of the original array and view
does not own the data. When we make changes to the view it affects the original array,
and when changes are made to the original array it affects the view.
 Example
◦ import numpy as np
◦ # To begin with, a is 3X2 array
◦ a = np.arange(6).reshape(3,2)
◦ print 'Array a:'
◦ print a
◦ print 'Create view of a:'
◦ b = a.view()
◦ print b
◦ print 'id() for both the arrays are different:'
◦ print 'id() of a:'
◦ print id(a)
◦ print 'id() of b:'
◦ print id(b)
◦ # Change the shape of b. It does not change the shape of a
◦ b.shape = 2,3
◦ print 'Shape of b:'
◦ print b
◦ print 'Shape of a:‘
◦ print a
JKM BCA College
 Output
◦ Array a:
◦ [[0 1]
◦ [2 3]
◦ [4 5]]
◦ Create view of a:
◦ [[0 1]
◦ [2 3]
◦ [4 5]]
◦ id() for both the arrays are different:
◦ id() of a:
◦ 140424307227264
◦ id() of b:
◦ 140424151696288
◦ Shape of b:
◦ [[0 1 2]
◦ [3 4 5]]
◦ Shape of a:
◦ [[0 1]
◦ [2 3]
◦ [4 5]]

JKM BCA College


 This is also known as Deep Copy. The copy is completely a new array and copy
owns the data. When we make changes to the copy it does not affect the original
array, and when changes are made to the original array it does not affect the copy.
 Example
◦ import numpy as np
◦ # creating array
◦ arr = np.array([2, 4, 6, 8, 10])
◦ # creating copy of array
◦ c = arr.copy()
◦ # both arr and c have different id
◦ print("id of arr", id(arr))
◦ print("id of c", id(c))
◦ # changing original array
◦ # this will not effect copy
◦ arr[0] = 12
◦ # printing array and copy
◦ print("original array- ", arr)
◦ print("copy- ", c)
 Output:
◦ id of arr 35406048
◦ id of c 32095936
◦ original array- [12 4 6 8 10]
◦ copy- [ 2 4 6 8 10]

JKM BCA College


 This is also known as Deep Copy. The copy is completely a new array and copy
owns the data. When we make changes to the copy it does not affect the original
array, and when changes are made to the original array it does not affect the copy.
 Example
◦ import numpy as np
◦ # creating array
◦ arr = np.array([2, 4, 6, 8, 10])
◦ # creating copy of array
◦ c = arr.copy()
◦ # both arr and c have different id
◦ print("id of arr", id(arr))
◦ print("id of c", id(c))
◦ # changing original array
◦ # this will not effect copy
◦ arr[0] = 12
◦ # printing array and copy
◦ print("original array- ", arr)
◦ print("copy- ", c)
 Output:
◦ id of arr 35406048
◦ id of c 32095936
◦ original array- [12 4 6 8 10]
◦ copy- [ 2 4 6 8 10]

JKM BCA College


 NumPy contains a matrix library, i.e.
numpy.matlib which is used to configure
matrices instead of ndarray objects.
 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.
◦ shape: It is the tuple defining the shape of the matrix.
◦ dtype: It is the data type of the matrix.
◦ order: It is the insertion order of the matrix, i.e. C or F.

JKM BCA College


 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]]

JKM BCA College


 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.]]

JKM BCA College


 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)))
 Output:
◦ [[1. 1.]
◦ [1. 1.]]

JKM BCA College


 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.
◦ n: It represents the number of rows in the resulting matrix.
◦ m: It represents the number of columns, defaults to n.
◦ k: It is the index of diagonal.
◦ 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]]

JKM BCA College


 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]]

JKM BCA College


 numpy.matlib.rand() function
 This function is used to generate a matrix where
all the entries are initialized with random values.
 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]]

JKM BCA College


 The Linear Algebra module of NumPy offers
various methods to apply linear algebra on
any numpy array.
 One can find:
◦ rank, determinant, trace, etc. of an array.
◦ eigen values of matrices
◦ matrix and vector products (dot, inner, outer,etc.
product), matrix exponentiation
◦ solve linear or tensor equations and much more!

JKM BCA College


# Importing numpy as np
import numpy as np
 Output
A = np.array([[6, 1, 1], Rank of A: 3
[4, -2, 5],
[2, 8, 7]]) Trace of A: 11

# Rank of a matrix Determinant of A: -306.0


print("Rank of A:", np.linalg.matrix_rank(A))
Inverse of A:
# Trace of matrix A
[[ 0.17647059 -0.00326797 -0.02287582]
print("\nTrace of A:", np.trace(A))
[ 0.05882353 -0.13071895 0.08496732]
# Determinant of a matrix [-0.11764706 0.1503268 0.05228758]]
print("\nDeterminant of A:",
np.linalg.det(A)) Matrix A raised to power 3:
[336 162 228]
# Inverse of matrix A [406 162 469]
print("\nInverse of A:\n", np.linalg.inv(A)) [698 702 905]]

print("\nMatrix A raised to power 3:\n",


np.linalg.matrix_power(A, 3))

JKM BCA College

You might also like