0% found this document useful (0 votes)
3 views37 pages

Unit 2

This document outlines the curriculum for Unit 2 of a course on Advanced Python, focusing on the NumPy library. It covers topics such as NumPy introduction, array creation, data types, mathematical functions, and linear algebra, along with references for further reading. The document also includes a series of questions for assessment, categorized by marks.

Uploaded by

mirajoshi.1107
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
0% found this document useful (0 votes)
3 views37 pages

Unit 2

This document outlines the curriculum for Unit 2 of a course on Advanced Python, focusing on the NumPy library. It covers topics such as NumPy introduction, array creation, data types, mathematical functions, and linear algebra, along with references for further reading. The document also includes a series of questions for assessment, categorized by marks.

Uploaded by

mirajoshi.1107
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/ 37

CS – 33 : Programming in Advance Python – 2

B.C.A. Semester – 6th


Unit : 2
Python Numpy
NumPy Introduction
 Environment Setup
 NumPy Ndarray
 NumPy Data Types
 NumPy Array Creation
 Array From Existing Data
 Arrays within the numerical range
 NumPy Broadcasting
 NumPy Array Iteration
 NumPy Bitwise Operators
 NumPy String Functions
 NumPy Mathematical Functions
 Statistical Functions
 Sorting & Searching
 Copies and Views
 Matrix Library
 NumPy Linear Algebra

References:
 Alex Martelli, Python Cookbook, O’REILLY 1)
 John V Guttag. “Introduction to Computation and Programming Using Python”, Prentice Hall of India
 Wesley J Chun, Core Python Applications Programming, 3rd Edition. Pearson
 https://www.geeksforgeeks.org/python-gui-tkinter
 https://www.tutorialspoint.com/python/python
 https://www.javatpoint.com/python
 https://www.numpy.org/
 https://www.djangoproject.com/start/

Dr. Dhaval Kher Head of Department [BCA | M.Sc(IT&CA) ]


Dr. Virambhai R. Godhaniya I. T. College
B/h. Amar Polyfills, Rajkot- National Highway, Opp. New Airport, Porbandar - 360 578. (Gujarat).
Mobile : 9879870002| E-Mail : [email protected] | www.drvrgit.com
Unit-2 Python Numpy
INDEX

1 MARKS QUESTIONS: ................................................................................................................................................. 3


3 MARKS QUESTIONS: ................................................................................................................................................. 3
5 MARKS QUESTIONS: ................................................................................................................................................. 4
1. INTRODUCTION TO NUMPY ....................................................................................................................................... 5
WHAT IS NUMPY USED FOR? ................................................................................................................................................ 5
WHY USE NUMPY? ............................................................................................................................................................... 5
2. NUMPY ENVIRONMENT SETUP .................................................................................................................................. 5
IMPORT NUMPY IN PYTHON ................................................................................................................................................. 5
3. NUMPY N-D ARRAY AND ARRAY CREATION ............................................................................................................... 5
N-D ARRAY CREATION FROM LIST OF LISTS...................................................................................................................................... 6
CREATING N-D ARRAYS FROM SCRATCH .......................................................................................................................................... 6
CREATE N-D ARRAYS USING NP.ZEROS().......................................................................................................................................... 6
CREATE N-D ARRAY WITH A SPECIFIED VALUE .................................................................................................................................. 7
CREATE AN ARRAY WITH NP.ARANGE() ........................................................................................................................................... 7
CREATING ARRAYS WITH NP.RANDOM.RAND() ................................................................................................................................. 7
CREATE EMPTY N-D NUMPY ARRAY .............................................................................................................................................. 7
4. NUMPY DATA TYPES .................................................................................................................................................. 8
NUMPY DATA TYPES ................................................................................................................................................................... 8
CHECK DATA TYPE OF A NUMPY ARRAY .......................................................................................................................................... 8
CREATING NUMPY ARRAYS WITH A DEFINED DATA TYPE ................................................................................................................... 8
NUMPY TYPE CONVERSION........................................................................................................................................................... 9
5. NUMPY - ARRAY FROM EXISTING DATA ..................................................................................................................... 9
NUMPY.ASARRAY ........................................................................................................................................................................ 9
NUMPY.FROMBUFFER ................................................................................................................................................................ 10
NUMPY.FROMITER..................................................................................................................................................................... 11

6. NUMPY - ARRAYS WITHIN THE NUMERICAL RANGE .................................................................................................11


NUMPY.ARANGE ....................................................................................................................................................................... 11
NUMPY.LINSPACE ...................................................................................................................................................................... 12
NUMPY.LOGSPACE ..................................................................................................................................................................... 12

7. NUMPY BROADCASTING ...........................................................................................................................................12


8. NUMPY ARRAY ITERATION .......................................................................................................................................13
9. NUMPY BITWISE OPERATIONS ..................................................................................................................................15
NUMPY BITWISE AND OPERATION .............................................................................................................................................. 16
NUMPY BITWISE OR OPERATION ................................................................................................................................................ 17
NUMPY BITWISE NOT OPERATION .............................................................................................................................................. 18
BITWISE XOR OPERATOR ........................................................................................................................................................... 19
LEFT SHIFT OPERATOR ............................................................................................................................................................... 20
RIGHT SHIFT OPERATOR ............................................................................................................................................................. 21
10. NUMPY STRING FUNCTIONS .................................................................................................................................22
NUMPY.CHAR.ADD() METHOD EXAMPLE ........................................................................................................................................ 22
NUMPY.CHAR.MULTIPLY() METHOD EXAMPLE ................................................................................................................................. 22
NUMPY.CHAR.CENTER() METHOD EXAMPLE .................................................................................................................................... 22
NUMPY.CHAR.CAPITALIZE() METHOD EXAMPLE................................................................................................................................ 23

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 1
Unit-2 Python Numpy
NUMPY.CHAR.TITLE() METHOD EXAMPLE ....................................................................................................................................... 23
NUMPY.CHAR.LOWER() METHOD EXAMPLE..................................................................................................................................... 23
NUMPY.CHAR.UPPER() METHOD EXAMPLE...................................................................................................................................... 23
NUMPY.CHAR.SPLIT() METHOD EXAMPLE ....................................................................................................................................... 23
NUMPY.CHAR.SPLITLINES() METHOD EXAMPLE ................................................................................................................................ 23
NUMPY.CHAR.STRIP() METHOD EXAMPLE ....................................................................................................................................... 23
NUMPY.CHAR.JOIN() METHOD EXAMPLE ........................................................................................................................................ 24
NUMPY.CHAR.REPLACE() METHOD EXAMPLE ................................................................................................................................... 24
NUMPY.CHAR.ENCODE() AND DECODE() METHOD EXAMPLE ............................................................................................................... 24

11. NUMPY MATH FUNCTIONS ...................................................................................................................................24


1. TRIGONOMETRIC FUNCTIONS.............................................................................................................................................. 24
2. ARITHMETIC FUNCTIONS.................................................................................................................................................... 25
3. ROUNDING FUNCTIONS ..................................................................................................................................................... 26
12. NUMPY STATISTICAL FUNCTIONS .........................................................................................................................26
FINDING THE MINIMUM AND MAXIMUM ELEMENTS FROM THE ARRAY ................................................................................................. 26
THE NUMPY.AMIN() AND NUMPY.AMAX()...................................................................................................................................... 26
NUMPY.PTP() FUNCTION............................................................................................................................................................. 27
NUMPY.PERCENTILE() FUNCTION .................................................................................................................................................. 27
THE NUMPY.MEDIAN() FUNCTION: ............................................................................................................................................... 28
THE NUMPY.MEAN() FUNCTION: .................................................................................................................................................. 28
THE NUMPY.AVERAGE() FUNCTION: .............................................................................................................................................. 28
13. NUMPY SORTING AND SEARCHING ......................................................................................................................28
NUMPY.SORT(INPUT, AXIS, KIND, ORDER) ...................................................................................................................................... 28
NUMPY.ARGSORT() FUNCTION ..................................................................................................................................................... 29
NUMPY.LEXSORT() FUNCTION ...................................................................................................................................................... 29
NUMPY.NONZERO() FUNCTION .................................................................................................................................................... 30
NUMPY.WHERE() FUNCTION ........................................................................................................................................................ 30

14. NUMPY COPIES AND VIEWS..................................................................................................................................30


ARRAY ASSIGNMENT.................................................................................................................................................................. 30
THE ID() FUNCTION ................................................................................................................................................................... 30
NDARRAY.VIEW() METHOD.......................................................................................................................................................... 31
NDARRAY.COPY() METHOD.......................................................................................................................................................... 32

15. NUMPY MATRIX LIBRARY ............................................................................................................................32


NUMPY.MATLIB.EMPTY() FUNCTION ..................................................................................................................................... 33
NUMPY.MATLIB.ZEROS() FUNCTION ...................................................................................................................................... 33
NUMPY.MATLIB.ONES() FUNCTION ........................................................................................................................................ 33
NUMPY.MATLIB.EYE() FUNCTION .......................................................................................................................................... 33
NUMPY.MATLIB.IDENTITY() FUNCTION ................................................................................................................................. 34
NUMPY.MATLIB.RAND() FUNCTION ....................................................................................................................................... 34

16. NUMPY LINEAR ALGEBRA .....................................................................................................................................34


NUMPY.DOT() FUNCTION ............................................................................................................................................................ 34
NUMPY.VDOT() FUNCTION .......................................................................................................................................................... 35
NUMPY.INNER() FUNCTION ......................................................................................................................................................... 35
NUMPY.MATMUL() FUNCTION ..................................................................................................................................................... 35
NUMPY DETERMINANT ............................................................................................................................................................... 35
THE NUMPY.LINALG.DET() FUNCTION ............................................................................................................................................ 35
NUMPY.LINALG.SOLVE() FUNCTION ............................................................................................................................................... 36
NUMPY.LINALG.INV() FUNCTION .................................................................................................................................................. 36

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 2
Unit-2 Python Numpy

1 Marks Questions:
1. NumPy version string is stored under np.___________ attribute.
2. _________ attribute of ndarray object return number of dimension.
3. numpy.array(5000) create ________ dimensional ndarray object.
4. Define NumPy.
5. Write Full form of Numpy.
6. Listout bitwise operators in Numpy.
7. Numpy stands for __________.
8. Numpy performs array oriented computing (True/False)
9. Ndarray stand for ________.
10. NumPy was created by _______.
11. NumPy contains a Matrix Library_______.
12. Which function is used to calculate the middle element of data?
13. NumPy package is capable to do fast operations on arrays. (True/False)
14. NumPy arrays can be ________.
a. Indexed
b. Sliced
c. Iterated
d. All of the mentioned above
15. NumPy arrays can be ______.
a. Indexed
b. Sliced
c. Iterated
d. All of the mentioned above
16. NumPy arrays can be ___.
a. Indexed
b. Sliced
c. Iterated
d. All of the mentioned above

3 Marks Questions:

1. Explain np.array( ) and np.asarray( ) with an example.


2. Explain np.frombuffer( ) and np.fromiter( ) with an example.
3. Explain np.arange( ) and np.linspace( ) with an example.
4. Explain numpy bitwise operator.
5. List out Numpy data types in brief
6. Explain sorting and searching operation in Numpy in brief.
7. What is difference between copy and view?
8. Explain any 3 string functions with suitable example.
9. Explain Numpy Ndarray.
10. Explain Numpy bitwise operators.
11. What is Numpy? How it is useful?
12. What is Ndarray? Describe its dimensions.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 3
Unit-2 Python Numpy

13. Explain multiply(), title() and join() ofNumPy.


14. Differentiate copies and views in Numpy.
15. Explain numpy array creation from existing data.

5 Marks Questions:
1. Explain Numpy Brodcasting with an example.
2. Explain any five Numpy String functions.
3. List out any five mathematical functions with suitable example.
4. Explain Numpy Statistical funcitons with example.
5. Explain numpy array iteration with suitable example.
6. Explain numpy linear algebra with example.
7. Explain sorting and searching with example.
8. Explain Numpy Data types.
9. Explain Numpy matrix library.
10. Explain Numpy Broadcasting.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 4
Unit-2 Python Numpy

1. Introduction to NumPy
NumPy is a Python library created in 2005 that performs numerical calculations. It is generally used
for working with arrays.
NumPy also includes a wide range of mathematical functions, such as linear algebra, Fourier
transforms, and random number generation, which can be applied to arrays.
What is NumPy Used for?
NumPy is an important library generally used for:
 Machine Learning
 Data Science
 Image and Signal Processing
 Scientific Computing
 Quantum Computing
Why Use NumPy?
Some of the major reasons why we should use NumPy are:
1. Faster Execution: In Python, we use lists to work with arrays. But when it comes to large
array operations, Python lists are not optimized enough.
Numpy arrays are optimized for complex mathematical and statistical operations. Operations
on NumPy are up to 50x faster than iterating over native Python lists using loops.
Here're some of the reasons why NumPy is so fast:
 Uses specialized data structures called numpy arrays.
 Created using high-performance languages like C and C++.
2. Used with Various Libraries: NumPy is heavily used with various libraries like Pandas,
Scipy, scikit-learn, etc.

2. NumPy Environment Setup


NumPy doesn't come bundled with Python. We have to install it using the python pip installer. Execute
the following command.
pip install numpy
Import NumPy in Python
We can import NumPy in Python using the import statement.
import numpy as np ( or simply import numpy)
The code above imports the numpy library in our program as an alias np.
After this import statement, we can use NumPy functions and objects by calling them with np.
Note:
 If we import NumPy without an alias using import numpy, we can create an array using the
numpy.array() function.
 Using an alias np is a common convention among Python programmers, as it makes it easier
and quicker to refer to the NumPy library in your code.

3. NumPy N-D Array and Array Creation


 NumPy is not restricted to 1-D arrays, it can have arrays of multiple dimensions, also known as
N-dimensional arrays or ndarrays.
 An N-dimensional array refers to the number of dimensions in which the array is organized.
 An array can have any number of dimensions and each dimension can have any number of
elements.
 For example, a 2D array represents a table with rows and columns, while a 3D array represents a
cube with width, height, and depth.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 5
Unit-2 Python Numpy

 There are multiple techniques to create N-d arrays in NumPy, and we will explore each of them
below.
N-D Array Creation From List of Lists
 To create an N-dimensional NumPy array from a Python List, we can use the np.array() function
and pass the list as an argument.
Create a 2-D NumPy Array
Let's create a 2D NumPy array with 2 rows and 4 columns using lists.
import numpy as np
# create a 2D array with 2 rows and 4 columns
array1 = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
print(array1)
In the above example, we first created a 2D list (list of lists) [[1, 2, 3, 4], [5, 6, 7, 8]] with
2 rows and 4 columns. We then passed the list to the np.array() function to create a 2D array.

Create a 3-D NumPy Array


Let's say we want to create a 3-D NumPy array consisting of two "slices" where each slice has 3
rows and 4 columns.
Here's how we create our desired 3-D array,
import numpy as np
# create a 3D array with 2 "slices", each of 3 rows and 4 columns
array1 = np.array([[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
print(array1)
Creating N-d Arrays From Scratch
We saw how to create N-d NumPy arrays from Python lists. Now we'll see how we can create them
from scratch.
To create multidimensional arrays from scratch we use functions such as
 np.zeros()
 np.arange()
 np.random.rand()
Create N-D Arrays using np.zeros()
The np.zeros() function allows us to create N-D arrays filled with all zeros. For example,
import numpy as np
# create 2D array with 2 rows and 3 columns filled with zeros
array1 = np.zeros((2, 3))
print("2-D Array: ")
print(array1)
# create 3D array with dimensions 2x3x4 filled with zeros
array2 = np.zeros((2, 3, 4))
print("\n3-D Array: ")
print(array2)

In the above example, we have used the np.zeros() function to create a 2-D array and 3-D array
filled with zeros respectively.
 np.zeros((2, 3)) - returns a zero filled 2-D array with 2 rows and 3 columns
 np.zeros((2, 3, 4)) - returns a zero filled 3-D array with 2 slices, each slice having 3 rows
and 4 columns.
Note: Similarly we can use np.ones() to create an array filled with values 1.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 6
Unit-2 Python Numpy

Create N-D Array with a Specified Value


In NumPy, we can use the np.full() function to create a multidimensional array with a specified
value.
For example, to create a 2-D array with the value 5, we can do the following:
import numpy as np
# Create a 2-D array with elements initialized to 5
numpy_array = np.full((2, 2), 5)
print("Array:", numpy_array)
Here, we have used the np.full() function to create a 2-D array where all elements are initialized
to 5.
Create an Array With np.arange()
The np.arange() function returns an array with values within a specified interval. For example,
import numpy as np
# create an array with values from 0 to 4
array1 = np.arange(5)
print("Using np.arange(5):", array1)
# create an array with values from 1 to 8 with a step of 2
array2 = np.arange(1, 9, 2)
print("Using np.arange(1, 9, 2):",array2)
Output
Using np.arange(5): [0 1 2 3 4]
Using np.arange(1, 9, 2): [1 3 5 7]
In the above example, we have created arrays using the np.arange() function.
 np.arange(5) - create an array with 5 elements, where the values range from 0 to 4
 np.arange(1, 9, 2) - create an array with 5 elements, where the values range from 1 to 8
with a step of 2.

Creating Arrays With np.random.rand()


The np.random.rand() function is used to create an array of random numbers.
Let's see an example to create an array of random numbers,
import numpy as np
# create a 2D array of 2 rows and 2 columns of random numbers
array1 = np.random.rand(2, 2)
print("2-D Array: ")
print(array1)
# create a 3D array of shape (2, 2, 2) of random numbers
array2 = np.random.rand(2, 2, 2)
print("\n3-D Array: ")
print(array2)
Here,
 np.random.rand(2, 2) - creates a 2D array of 2 rows and 2 columns of random numbers.
 np.random.rand(2, 2, 2) - creates a 3D array with 2 slices, each slice having 2 rows and 2
columns of random numbers.

Create Empty N-D NumPy Array


To create an empty N-D NumPy array, we use the np.empty() function. For example,
import numpy as np

# create an empty 2D array with 2 rows and 2 columns


array1 = np.empty((2, 2))
print("2-D Array: ")
print(array1)
# create an empty 3D array of shape (2, 2, 2)
array2 = np.empty((2, 2, 2))
print("\n3-D Array: ")
print(array2)

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 7
Unit-2 Python Numpy

In the above example, we used the np.empty() function to create an empty 2-D array and a 3-D
array respectively.
If we look into the output of the code, we can see the empty array is actually not empty, it has
some values in it. It is because although we are creating an empty array, NumPy will try to add
some value to it. The values stored in the array are arbitrary and have no significance value.

4. NumPy Data Types


A data type is a way to specify the type of data that will be stored in an array. For example,
array1 = np.array([2, 4, 6])
Here, the array1 array contains three integer elements, so the data type is Integer(int32)), by default.
NumPy provides us with several built-in data types to efficiently represent numerical data.

NumPy Data Types


NumPy offers a wider range of numerical data types than what is available in Python. Here's the list
of most commonly used numeric data types in NumPy:
1. int8, int16, int32, int64 - signed integer types with different bit sizes
2. uint8, uint16, uint32, uint64 - unsigned integer types with different bit sizes
3. float32, float64 - floating-point types with different precision levels
4. complex64, complex128 - complex number types with different precision levels

Check Data Type of a NumPy Array


To check the data type of a NumPy array, we can use the dtype attribute. For example,
import numpy as np
# create an array of integers
array1 = np.array([2, 4, 6])
# check the data type of array1
print(array1.dtype)
In the above example, we have used the dtype attribute to check the data type of the array1 array.
Since array1 is an array of integers, the data type of array1 is inferred as int64 by default.

Example: Check Data Type of NumPy Array


import numpy as np
# create an array of integers
int_array = np.array([-3, -1, 0, 1])
# create an array of floating-point numbers
float_array = np.array([0.1, 0.2, 0.3])
# create an array of complex numbers
complex_array = np.array([1+2j, 2+3j, 3+4j])
# check the data type of int_array
print(int_array.dtype) # prints int64
# check the data type of float_array
print(float_array.dtype) # prints float64
# check the data type of complex_array
print(complex_array.dtype) # prints complex128
Here, we have created types of arrays and checked the default data types of these arrays using the
dtype attribute.
 int_array - contains four integer elements whose default data type is int64
 float_array - contains three floating-point numbers whose default data type is float64
 complex_array - contains three complex numbers whose default data type is complex128

Creating NumPy Arrays With a Defined Data Type


In NumPy, we can create an array with a defined data type by passing the dtype parameter while
calling the np.array() function. For example,
import numpy as np

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 8
Unit-2 Python Numpy
# create an array of 32-bit integers
array1 = np.array([1, 3, 7], dtype='int32')
print(array1, array1.dtype)
In the above example, we have created a NumPy array named array1 with a defined data type.
Notice the code,
np.array([1, 3, 7], dtype='int32')
Here, inside np.array(), we have passed an array [1, 3, 7] and set the dtype parameter to
int32.
Since we have set the data type of the array to int32, each element of the array is represented as a
32-bit integer.
Example: Creating NumPy Arrays With a Defined Data Type
import numpy as np
# create an array of 8-bit integers
array1 = np.array([1, 3, 7], dtype='int8')
# create an array of unsigned 16-bit integers
array2 = np.array([2, 4, 6], dtype='uint16')
# create an array of 32-bit floating-point numbers
array3 = np.array([1.2, 2.3, 3.4], dtype='float32')
# create an array of 64-bit complex numbers
array4 = np.array([1+2j, 2+3j, 3+4j], dtype='complex64')
# print the arrays and their data types
print(array1, array1.dtype)
print(array2, array2.dtype)
print(array3, array3.dtype)
print(array4, array4.dtype)

NumPy Type Conversion


In NumPy, we can convert the data type of an array using the astype() method. For example,
import numpy as np
# create an array of integers
int_array = np.array([1, 3, 5, 7])
# convert data type of int_array to float
float_array = int_array.astype('float')
# print the arrays and their data types
print(int_array, int_array.dtype)
print(float_array, float_array.dtype)
Here, int_array.astype('float') converts the data type of int_array from int64 to float64
using astype().

5. NumPy - Array From 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.
Sr.No. Parameter & Description
1 A Input data in any form such as list, list of tuples, tuples, tuple of tuples or tuple
of lists
2 Dtype By default, the data type of input data is applied to the resultant ndarray
3 Order C (row major) or F (column major). C is default

Note :

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 9
Unit-2 Python Numpy

In NumPy, both array() and asarray() are used to create arrays. Here's the key difference:
array():
 Creates a new copy of the input data, even if the input is already a NumPy array.
 Offers more flexibility with arguments like dtype and order.
asarray():
 Converts the input to a NumPy array without making a copy if the input is
already an array.
 More efficient if you don't need to explicitly control the data type or memory
layout.
When to use which:
 array():
Use this when you need to ensure a new copy of the data or want to explicitly specify
the data type or memory layout.
 asarray():
Use this for efficient conversion when you don't need a copy of the data and are okay
with the default data type and memory layout.

The following examples show how you can use the asarray function.
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]
Example 2
# dtype is set
import numpy as np
x = [1,2,3]
a = np.asarray(x, dtype = float)
print a
Now, the output would be as follows −
[ 1. 2. 3.]
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]
Example 4
# ndarray from list of tuples
import numpy as np
x = [(1,2,3),(4,5)]
a = np.asarray(x)
print a
Here, the output would be as follows −
[(1, 2, 3) (4, 5)]
numpy.frombuffer
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.
Sr.No. Parameter & Description
1 Buffer Any object that exposes buffer interface
By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 10
Unit-2 Python Numpy

2 Dtype Data type of returned ndarray. Defaults to float


3 Count The number of items to read, default -1 means all data
4 Offset The starting position to read from. Default is 0
Example
The following examples demonstrate the use of frombuffer function.
import numpy as np
s = b'Hello World'
a = np.frombuffer(s, dtype = 'S1')
print a
Here is its output −
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
numpy.fromiter
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.
Sr.No. Parameter & Description
1 Iterable Any iterable object
2 Dtype Data type of resultant array
3 Count The number of items to be read from iterator. Default is -1 which means all
data to be read
The following examples show how to use the built-in range() function to return a list object. An
iterator of this list is used to form an ndarray object.
Example 1
# create list object using range function
import numpy as np
list = range(5)
print list
Its output is as follows −
[0, 1, 2, 3, 4]
Example 2
# 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.]

6. NumPy - Arrays within the numerical range


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.
Parameter & Description
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

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 11
Unit-2 Python Numpy

numpy.linspace
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.
Parameter & Description
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
numpy.logspace
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.
Parameter & Description
Start:The starting point of the sequence is basestart
Stop:The final value of sequence is basestop
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

7. NumPy Broadcasting
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.
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.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 12
Unit-2 Python Numpy

 Array having too few dimensions can have its shape prepended with a dimension of length 1, so
that the above stated property is true.

8. NumPy Array Iteration


NumPy provides an iterator object, i.e., nditer which can be used to iterate over the given array using
python standard Iterator interface.
Consider the following example.
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);
print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
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

Order of the iteration doesn't follow any special ordering like row-major or column-order. However,
it is intended to match the memory layout of the array.
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

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 13
Unit-2 Python Numpy

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
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]]
Printing the transpose of the array:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the transposed array
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
[[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the C-style array:
1 2 10 2 4 20 3 5 39 4 6 3 [[ 1 2 10]
[ 2 4 20]
[ 3 5 39]
[ 4 6 3]]
Iterating over the F-style array:
1 2 3 4 2 4 5 6 10 20 39 3

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 14
Unit-2 Python Numpy

We can mention the order 'C' or 'F' while defining the Iterator object itself. Consider the following
example.
Example
import numpy as np
1. 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")
print("\nIterating over the C-style array:\n")
for x in np.nditer(at, order = 'C'):
print(x,end=' ')
Output:
Iterating over the transposed array
1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:
Iterating over the C-style array:
1 2 10 2 4 20 3 5 39 4 6 3

Array Values Modification


We can not modify the array elements during the iteration since the op-flag associated with the Iterator
object is set to readonly.
However, we can set this flag to readwrite or write only to modify the array values. Consider the
following example.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("\nPrinting the original array:\n")
print(a)
print("\nIterating over the modified array\n")
for x in np.nditer(a, op_flags = ['readwrite']):
x[...] = 3 * x;
print(x,end = ' ')
Output:
Printing the original array:
[[ 1 2 3 4]
[ 2 4 5 6]
[10 20 39 3]]
Iterating over the modified array
3 6 9 12 6 12 15 18 30 60 117 9

9. NumPy Bitwise Operations


Bitwise operations are used to manipulate the individual bits of binary values.
NumPy provides several bitwise operations that allow us to perform bitwise operations on arrays of
integers.
Bitwise Operators Available in NumPy

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 15
Unit-2 Python Numpy

In NumPy, there are 6 basic bitwise operators available.


Bitwise Operators Description
bitwise_and() calculates bitwise AND operation
bitwise_or() calculates bitwise OR operation
invert() calculates bitwise NOT operation
bitwise_xor() calculates bitwise XOR operation
left_shift() shifts the bits of an integer to the left
right_shift() shift the bits of an integer to the right

NumPy Bitwise AND Operation


The bitwise_and() function returns 1 if and only if both the operands are 1. Otherwise, it returns 0.
The bitwise AND operation on a and b can be represented in the table below.
a b bitwise_and(a, b)
0 0 0
0 1 0
1 0 0
1 1 1
Note: The table above is known as the "Truth Table" for the bitwise AND operator.
Let's take a look at the bitwise AND operation of two integers 12 and 25:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
# bitwise AND Operation of 12 and 25
00001100
AND 00011001
_____________
00001000 = 8 (In decimal)

Example: NumPy Bitwise AND Operation


import numpy as np
int1 = 12
int2 = 25
# perform bitwise AND operation
result = np.bitwise_and(int1, int2)
print (result)
# Output: 8
In this example, we have declared two variables int1 and int2. Notice the line,
result = np.bitwise_and(int1, int2)
Here, we are performing bitwise AND operation between int1 and int2 using bitwise_and().

Example: NumPy Bitwise AND Operation on two Arrays (Element-wise)


import numpy as np
# create two arrays
array1 = np.array([12, 5, 8])
array2 = np.array([25, 12, 2])

# perform bitwise AND operation


result = np.bitwise_and(array1, array2)
print("array1: ", array1)
print("array2: ", array2)
print("Result of bitwise AND operation: ", result)
Output
array1: [12 5 8]

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 16
Unit-2 Python Numpy

array2: [25 12 2]
Result of bitwise AND operation: [8 4 0]
Here, np.bitwise_and(array1, array2) performs a bitwise AND operation between the corresponding
elements of the two arrays: array1 and array2.
NumPy Bitwise OR Operation
The bitwise_or() function returns 1 if at least one of the operands is 1. Otherwise, it returns 0.
The bitwise OR operation on a and b can be represented in the table below.
a b bitwise_or(a, b)
0 0 0
0 1 1
1 1 1
1 0 1
Note: The table above is known as the "Truth Table" for the bitwise OR operator.
Let's take a look at the bitwise OR operation of two integers 12 and 25:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
# bitwise OR Operation of 12 and 25
00001100
OR 00011001
____________
00011101 = 29 (In decimal)

Example: NumPy Bitwise OR Operation


import numpy as np
int1 = 12
int2 = 25
# perform bitwise OR operation
result = np.bitwise_or(int1, int2)
print (result)
# Output: 29
In this example, we have declared two variables int1 and int2. Here, notice the line,
result = np.bitwise_or(int1, int2)
Here, we are performing bitwise OR operation between int1 and int2 using bitwise_or().

Example: NumPy Bitwise OR Operation on two Arrays (Element-wise)


import numpy as np

# create two arrays


array1 = np.array([12, 5, 8])
array2 = np.array([25, 12, 2])
# perform bitwise OR operation
result = np.bitwise_or(array1, array2)
print("array1: ", array1)
print("array2: ", array2)
print("Result of bitwise OR operation: ", result)
Output
array1: [12 5 8]
array2: [25 12 2]
Result of bitwise OR operation: [29 13 10]
Here, np.bitwise_or(array1, array2) performs a bitwise OR operation between the corresponding
elements of the two arrays: array1 and array2.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 17
Unit-2 Python Numpy

NumPy Bitwise NOT Operation


In NumPy, the invert() function inverts the bit( 0 becomes 1, 1 becomes 0).

Swift NOT Operation


The bitwise NOT operation on a can be represented in the table below.
a invert(a)
0 1
1 0
Note: The table above is known as the "Truth Table" for the bitwise NOT operator.
It is important to note that the bitwise NOT of any integer N is equal to -(N + 1). For example,
Consider an integer 35. As per the rule, the bitwise NOT of 35 should be -(35 + 1) = -36. Now, let's
see if we get the correct answer or not.
35 = 00100011 (In Binary)
# Using bitwise NOT operator
NOT 00100011
________
11011100
In the above example, the bitwise NOT of 00100011 is 11011100. Here, if we convert the result into
decimal we get 220.
However, it is important to note that we cannot directly convert the result into decimal and get the
desired output. This is because the binary result 11011100 is also equivalent to -36.
To understand this we first need to calculate the binary output of -36. We use 2's complement to
calculate the binary of negative integers.
2's complement
The 2's complement of a number N gives -N. It is computed by inverting the bits(0 to 1 and 1 to 0)
and then adding 1. For example,
36 = 00100100 (In Binary)
1's Complement = 11011011
2's Complement :
11011011
+ 1
________
11011100
Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the
bitwise complement of 35 that we have calculated in the previous section.
Hence, we can say that the bitwise complement of 35 = -36.
Example: NumPy Bitwise NOT Operation
import numpy as np
int1 = 35
# perform bitwise NOT operation
result = np.invert(int1)
print (result)
# Output: -36
In this example, we have performed the bitwise NOT operation on 35.
The bitwise complement of 35 = - (35 + 1) = –36
i.e. invert(35) = -36

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 18
Unit-2 Python Numpy

This is exactly what we got in the output.


Example: NumPy Bitwise NOT Operation on an Array
import numpy as np

# create two arrays


array1 = np.array([35, 12, 8])

# perform bitwise NOT operation


result = np.invert(array1)

print("array1: ", array1)


print("Result of bitwise NOT operation: ", result)
Output
array1: [35 12 8]
Result of bitwise NOT operation: [-36 -13 -9]
As we can see, np.invert(array1) performs a bitwise NOT operation on elements of array1.

Bitwise XOR Operator


The bitwise_xor() function returns 1 if and only if one of the operands is 1. However, if both the
operands are 0, or if both are 1, then the result is 0.
The bitwise XOR operation on a and b can be represented in the table below.
a b bitwise_xor(a,b)
0 0 0
0 1 1
1 0 1
1 1 0
Let us look at the bitwise XOR operation of two integers 12 and 25:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
# bitwise XOR Operation of 12 and 25
00001100
XOR 00011001
____________
00010101 = 21 (In decimal)
Example: Bitwise XOR Operator
import numpy as np
int1 = 12
int2 = 25
# perform bitwise XOR operation
result = np.bitwise_xor(int1, int2)
print (result)
# Output: 21
Here, we are performing bitwise XOR between 12 and 25 using the bitwise_xor() function.

Example: NumPy Bitwise XOR Operation on two Arrays (Element-wise)


import numpy as np
# create two arrays
array1 = np.array([12, 5, 8])
array2 = np.array([25, 12, 2])
# perform bitwise XOR operation
result = np.bitwise_xor(array1, array2)
print("array1: ", array1)

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 19
Unit-2 Python Numpy

print("array2: ", array2)


print("Result of bitwise XOR operation: ", result)
Output
array1: [12 5 8]
array2: [25 12 2]
Result of bitwise XOR operation: [21 9 10]
Here, np.bitwise_xor(array1, array2) performs a bitwise XOR operation between the corresponding
elements of the two arrays: array1 and array2.

Left Shift Operator


We use the left_shift() function to shift all bits towards the left by a specified number of bits.

NumPy Left Shift Operation


As we can see from the image above,
We have a 4-digit number. When we perform a 1 bit left shift operation on it, each bit is shifted to the
left by 1 bit.
As a result, the left-most bit is discarded, while the right-most bit remains vacant. This vacancy is
replaced by 0.

Example: NumPy Left Shift Operation


import numpy as np
int1 = 3
# perform left shift operation
result = np.left_shift(int1,2)
print (result)
# Output: 12
In this example, we have created a variable int1 with the value 3. Notice the statement
result = np.left_shift(int1, 2)
Here, we are performing 2 bits left shift operation on int1.

Example: Bitwise Left Shift Operation on an Array


import numpy as np
# create two arrays
array1 = np.array([3, 5, 8])
bit_shift = np.array([2, 4, 2])
# perform bitwise left shift operation
result = np.left_shift(array1, bit_shift)
print("array1: ", array1)
print("Result of bitwise left shift operation: ", result)
Output
array1: [3 5 8]
Result of bitwise left shift operation: [12 80 32]
Here, np.left_shift(array1, bit_shift) performs a bitwise left shift operation on the elements of the
array1 array.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 20
Unit-2 Python Numpy

Right Shift Operator


We use the right_shift() function to shift all bits towards the right by a specified number of bits.

NumPy Right Shift Operation


As we can see from the image above,
We have a 4-digit number. When we perform a 1-bit right shift operation on it, each bit is shifted to
the right by 1 bit.
As a result, the right-most bit is discarded, while the left-most bit remains vacant. This vacancy is
replaced by 0 for unsigned numbers.
For signed numbers, the sign bit (0 for positive number, 1 for negative number) is used to fill the
vacated bit positions.
Note: Signed integers represent both positive and negative integers while an unsigned integer only
represents positive integers.

Example: NumPy Right Shift Operation


import numpy as np
int1 = 4
# perform right shift operation
result = np.right_shift(int1,2)
print (result) # Output: 1
int2 = -4
# perform right shift operation
result = np.right_shift(int2,2)
print (result) # Output: -1
In this example, we are performing 2 bits right shift operations on values 4 and -4.
As we can see the result is different for 4 and -4. This is because 4 is an unsigned integer so the
vacancy is filled with 0 and -4 is a negative signed number so vacancy is filled with 1.

Example: Bitwise Left Shift Operation on an Array


import numpy as np
# create two arrays
array1 = np.array([4, -4, 10, -11])
bit_shift = np.array([2, 2, 3, 3])
# perform bitwise right shift operation
result = np.right_shift(array1, bit_shift)
print("array1: ", array1)
print("Result of bitwise right shift operation: ", result)
Output
array1: [ 4 -4 10 -11]
Result of bitwise right shift operation: [ 1 -1 1 -2]
Here, np.right_shoft(array1, bit_shift) performs a bitwise right shift operation on the elements of the
array1 array.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 21
Unit-2 Python Numpy

10. NumPy String Functions


NumPy contains the following functions for the operations on the arrays of dtype string.
SN Function Description
1 add() It is used to concatenate the corresponding array elements (strings).
2 multiply() 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.
3 center() 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.
4 capitalize() It returns a copy of the original string in which the first letter of the
original string is converted to the Upper Case.
5 title() 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.
6 lower() It returns a copy of the string in which all the letters are converted into
the lower case.
7 upper() It returns a copy of the string in which all the letters are converted into
the upper case.
9 split() It returns a list of words in the string.
9 splitlines() It returns the list of lines in the string, breaking at line boundaries.
10 strip() Returns a copy of the string with the leading and trailing white spaces
removed.
11 join() It returns a string which is the concatenation of all the strings specified
in the given sequence.
12 replace() It returns a copy of the string by replacing all occurrences of a
particular substring with the specified one.
13 decode() It is used to decode the specified string element-wise using the
specified codec.
14 encode() It is used to encode the decoded string element-wise.

numpy.char.add() method example


import numpy as np
print("Concatenating two string arrays:")
print(np.char.add(['welcome','Hi'], [' to DRVRGIT', ' read python'] ))
Output:
Concatenating two string arrays:
['welcome to DRVRGIT' 'Hi read python']
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
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 *

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 22
Unit-2 Python Numpy

*****Javatpoint*****
numpy.char.capitalize() method example
import numpy as np
print("Capitalizing the string using capitalize()...")
print(np.char.capitalize("welcome to drvrgit"))
Output:
Capitalizing the string using capitalize()...
Welcome to drvrgit
numpy.char.title() method example
import numpy as np
print("Converting string into title cased version...")
print(np.char.title("welcome to drvrgit"))
Output:
Converting string into title cased version...
Welcome To Drvrgit
numpy.char.lower() method example
import numpy as np
print("Converting all the characters of the string into lowercase...")
print(np.char.lower("WELCOME TO DRVRGIT"))
Output:
Converting all the characters of the string into lowercase...
welcome to drvrgit
numpy.char.upper() method example
import numpy as np
print("Converting all the characters of the string into uppercase...")
print(np.char.upper("Welcome To Drvrgit"))
Output:
Converting all the characters of the string into uppercase...
WELCOME TO DRVRGIT
numpy.char.split() method example
import numpy as np
print("Splitting the String word by word..")
print(np.char.split("Welcome To drvrgit"),sep = " ")
Output:
Splitting the String word by word..
['Welcome', 'To', 'drvrgit']
numpy.char.splitlines() method example
import numpy as np
print("Splitting the String line by line..")
print(np.char.splitlines("Welcome\nTo\nDrvrgit"))
Output:
Splitting the String line by line..
['Welcome', 'To', 'Drvrgit']
numpy.char.strip() method example
import numpy as np
str = " welcome to drvrgit "
print("Original String:",str)
print("Removing the leading and trailing whitespaces from the string")
print(np.char.strip(str))
Output:
Original String: welcome to drvrgit

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 23
Unit-2 Python Numpy

Removing the leading and trailing whitespaces from the string


welcome to javatpoint
numpy.char.join() method example
import numpy as np
print(np.char.join(':','HM'))
Output:
H:M
numpy.char.replace() method example
import numpy as np
str = "Welcome to Drvrgit"
print("Original String:",str)
print("Modified String:",end=" ")
print(np.char.replace(str, "Welcome to","www."))
Output:
Original String: Welcome to Drvrgit
Modified String: www. Drvrgit
numpy.char.encode() and decode() method example
import numpy as np
enstr = np.char.encode("welcome to drvrgit", 'cp500')
dstr =np.char.decode(enstr, 'cp500')
print(enstr)
print(dstr)
Output:
b'\xa6\x85\x93\x83\x96\x94\x85@\xa3\x96@\x84\x99\xa5\x99\x87\x89\xa3'
welcome to drvrgit

11. NumPy Math Functions


Numpy provides a wide range of mathematical functions that can be performed on arrays.
Let's explore three different types of math functions in NumPy:
1. Trigonometric Functions
2. Arithmetic Functions
3. Rounding Functions
1. Trigonometric Functions
NumPy provides a set of standard trigonometric functions to calculate the trigonometric ratios (sine,
cosine, tangent, etc.)
Here's a list of commonly used trigonometric functions in NumPy.
Trigonometric Function Computes (in radians)
sin() the sine of an angle
cos() cosine of an angle
tan() tangent of an angle
arcsin() the inverse sine
arccos() the inverse cosine
arctan() the inverse tangent
degrees() converts an angle in radians to degrees
radians() converts an angle in degrees to radians
Let's see the examples.
import numpy as np
# array of angles in radians
angles = np.array([0, 1, 2])
print("Angles:", angles)

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 24
Unit-2 Python Numpy

# compute the sine of the angles


sine_values = np.sin(angles)
print("Sine values:", sine_values)
# compute the inverse sine of the angles
inverse_sine = np.arcsin(angles)
print("Inverse Sine values:", inverse_sine)
Output
Angles: [0 1 2]
Sine values: [0. 0.84147098 0.90929743]
Inverse Sine values: [0. 1.57079633 nan]
In this example, the sin() and arcsin() functions calculate the sine and inverse sine values, respectively,
for each element in the angles array.
The resulting values are in radians.
Now let's see the examples for degrees() and radians().
import numpy as np
# define an angle in radians
angle = 1.57079633
print("Initial angle in radian:", angle)
# convert the angle to degrees
angle_degree = np.degrees(angle)
print("Angle in degrees:", angle_degree)
# convert the angle back to radians
angle_radian = np.radians(angle_degree)
print("Angle in radians (after conversion):", angle_radian)
Output
Initial angle in radian: 1.57079633
Angle in degrees: 90.0000001836389
Angle in radians (after conversion): 1.57079633
Here, we first initialized an angle in radians. Then we converted it to degrees using the degrees()
function.
Similarly, we used radians() to convert the degrees back to radians.
2. Arithmetic Functions
NumPy provides a wide range of arithmetic functions to perform on arrays.
Here's a list of various arithmetic functions along with their associated operators:
Operation Arithmetic Function Operator
Addition add() +
Subtraction subtract() -
Multiplication multiply() *
Division divide() /
Exponentiation power() **
Modulus mod() %
Let's see the examples.
import numpy as np
first_array = np.array([1, 3, 5, 7])
second_array = np.array([2, 4, 6, 8])
# using the add() function
result2 = np.add(first_array, second_array)
print("Using the add() function:",result2)
Output
Using the add() function: [ 3 7 11 15]
In the above example, first we created two arrays named: first_array and second_array. Then, we used
the add() function to perform element-wise addition respectively.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 25
Unit-2 Python Numpy

3. Rounding Functions
We use rounding functions to round the values in an array to a specified number of decimal places.
Here's a list of commonly used NumPy rounding functions:
Rounding Functions
Functions
round() returns the value rounded to the desired precision
floor() returns the values of array down to the nearest integer that is less than each
element
ceil() returns the values of array up to the nearest integer that is greater than each
element.
Let's see an example.
import numpy as np
numbers = np.array([1.23456, 2.34567, 3.45678, 4.56789])
# round the array to two decimal places
rounded_array = np.round(numbers, 2)
print(rounded_array)
# Output: [1.23 2.35 3.46 4.57]
Here, we used the round() function to round the values of array numbers. Notice the line,
np.round(numbers, 2)
We've given two arguments to the round() function.
numbers - the array whose values are to be rounded
2 - denotes the number of decimal places to which the array is rounded
Now, let's see the example of other NumPy rounding functions.
import numpy as np
array1 = np.array([1.23456, 2.34567, 3.45678, 4.56789])
print("Array after floor():", np.floor(array1))
print("Array after ceil():", np.ceil(array1))
Output
Array after floor(): [1. 2. 3. 4.]
Array after ceil(): [2. 3. 4. 5.]
In the above example, the floor() function rounds the values of array1 down to the nearest integer that
is less than or equal to each element.
Whereas, the ceil() function rounds the values of array1 up to the nearest integer that is greater than
or equal to each element.

12. Numpy statistical functions


Numpy provides various statistical functions which are used to perform some statistical data analysis.
In this section of the tutorial, we will discuss the statistical functions provided by the numpy.
Finding the minimum and maximum elements from the array
The numpy.amin() and numpy.amax()
This functions are used to find the minimum and maximum of the array elements along the specified
axis respectively.
Consider the following example.
Example
import numpy as np
a = np.array([[2,10,20],[80,43,31],[22,43,10]])
print("The original array:\n")
print(a)

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 26
Unit-2 Python Numpy

print("\nThe minimum element among the array:",np.amin(a))


print("The maximum element among the array:",np.amax(a))
print("\nThe minimum element among the rows of array",np.amin(a,0))
print("The maximum element among the rows of array",np.amax(a,0))
print("\nThe minimum element among the columns of array",np.amin(a,1))
print("The maximum element among the columns of array",np.amax(a,1))
Output:
The original array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]
The minimum element among the array: 2
The maximum element among the array: 80
The minimum element among the rows of array [ 2 10 10]
The maximum element among the rows of array [80 43 31]
The minimum element among the columns of array [ 2 31 10]
The maximum element among the columns of array [20 80 43]
numpy.ptp() function
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. Consider the following example.
Example
import numpy as np
a = np.array([[2,10,20],[80,43,31],[22,43,10]])
print("Original array:\n",a)
print("\nptp value along axis 1:",np.ptp(a,1))
print("ptp value along axis 0:",np.ptp(a,0))
Output:
Original array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]
ptp value along axis 1: [18 49 33]
ptp value along axis 0: [78 33 21]
numpy.percentile() function
The syntax to use the function is given below.
numpy.percentile(input, q, axis)
It accepts the following parameters.
input: It is the input array.
q: It is the percentile (1-100) which is calculated of the array element.
axis: It is the axis along which the percentile is to be calculated.
Consider the following example.
Example
import numpy as np
a = np.array([[2,10,20],[80,43,31],[22,43,10]])
print("Array:\n",a)
print("\nPercentile along axis 0",np.percentile(a, 10,0))
print("Percentile along axis 1",np.percentile(a, 10, 1))
Output:
Array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 27
Unit-2 Python Numpy

Percentile along axis 0 [ 6. 16.6 12. ]


Percentile along axis 1 [ 3.6 33.4 12.4]
Calculating median, mean, and average of array items
The numpy.median() function:
Median is defined as the value that is used to separate the higher range of data sample with a lower
range of data sample. The function numpy.median() is used to calculate the median of the multi-
dimensional or one-dimensional arrays.
The numpy.mean() function:
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.
The numpy.average() function:
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.
Consider the following example.
Example
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print("Array:\n",a)
print("\nMedian of array along axis 0:",np.median(a,0))
print("Mean of array along axis 0:",np.mean(a,0))
print("Average of array along axis 1:",np.average(a,1))

13. NumPy Sorting and Searching


Numpy provides a variety of functions for sorting and searching. There are various sorting algorithms
like quicksort, merge sort and heapsort which is implemented using the numpy.sort() function.
The kind of the sorting algorithm to be used in the sort operation must be mentioned in the function
call.
Let's discuss the sorting algorithm which is implemented in numpy.sort()
SN Algorithm Worst case complexity
1 Quick Sort O (n ^ 2)
2 Merge Sort O (n * log(n))
3 Heap Sort O (n * log(n))
The syntax to use the numpy.sort() function is given below.
numpy.sort(input, axis, kind, order)
It accepts the following parameters.
SN Parameter Description
1 input It represents the input array which is to be sorted.
2 Axis It represents the axis along which the array is to be sorted. If the axis is
not mentioned, then the sorting is done along the last available axis.
3 Kind It represents the type of sorting algorithm which is to be used while
sorting. The default is quick sort.
4 order It represents the filed according to which the array is to be sorted in the
case if the array contains the fields.
Consider the following example.
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))

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 28
Unit-2 Python Numpy

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'))
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)]
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.
Consider the following example.
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
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.
Consider the following example.
Example
import numpy as np
a = np.array(['a','b','c','d','e'])
b = np.array([12, 90, 380, 12, 211])
ind = np.lexsort((a,b))
print("printing indices of sorted data")
print(ind)
print("using the indices to sort the array")
for i in ind:
print(a[i],b[i])

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 29
Unit-2 Python Numpy

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
numpy.nonzero() function
This function is used to find the location of the non-zero elements from the array.
Consider the following example.
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]),)
numpy.where() function
This function is used to return the indices of all the elements which satisfies a particular condition.
Consider the following example.
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))
Output:
(array([1, 2, 4]),)
(array([0, 1, 1]), array([1, 0, 1]))

14. NumPy Copies and Views


The copy of an input array is physically stored at some other location and the content stored at that
particular location is returned which is the copy of the input array whereas the different view of the
same memory location is returned in the case of view.
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
It returns the universal identifier of the array similar to the pointer in C.
Consider the following example.
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)

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 30
Unit-2 Python Numpy

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]]
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.
Consider the following example.
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]

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 31
Unit-2 Python Numpy

[ 9 0 2 3]
[ 1 2 3 19]]
view
[[ 1 2 3]
[ 4 9 0]
[ 2 3 1]
[ 2 3 19]]
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.
Consider the following example.
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]]

15. NumPy Matrix Library


NumPy contains a matrix library, i.e. numpy.matlib which is used to configure matrices instead of
ndarray objects.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 32
Unit-2 Python Numpy

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.
Consider the following example.
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]]
numpy.matlib.zeros() function
This function is used to create the matrix where the entries are initialized to zero.
Consider the following example.
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.]]
numpy.matlib.ones() function
This function returns a matrix with all the elements initialized to 1.
Consider the following example.
Example
import numpy as np
import numpy.matlib
print(numpy.matlib.ones((2,2)))
Output:
[[1. 1.]
[1. 1.]]
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
Consider the following example.
Example
import numpy as np
import numpy.matlib

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 33
Unit-2 Python Numpy

print(numpy.matlib.eye(n = 3, M = 3, k = 0, dtype = int))


Output:
[[1 0 0]
[0 1 0]
[0 0 1]]
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.
Consider the following example.
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]]
numpy.matlib.rand() function
This function is used to generate a matrix where all the entries are initialized with random values.
Consider the following example.
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]]

16. NumPy Linear Algebra


Numpy provides the following functions to perform the different algebraic calculations on the input
data.
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.
numpy.dot() function
This function is used to return the dot product of the two matrices. It is similar to the matrix
multiplication. Consider the following example.
Example
import numpy as np
a = np.array([[100,200],[23,12]])
b = np.array([[10,20],[12,21]])

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 34
Unit-2 Python Numpy

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]
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.
Consider the following example.
Example
import numpy as np
a = np.array([[100,200],[23,12]])
b = np.array([[10,20],[12,21]])
vdot = np.vdot(a,b)
print(vdot)
Output:
5528
np.vdot(a,b) = 100 *10 + 200 * 20 + 23 * 12 + 12 * 21 = 5528
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.
Consider the following example.
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

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. Consider the following example.
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)

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
It is used to calculate the determinant of the matrix. Consider the following example.

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 35
Unit-2 Python Numpy

Example
import numpy as np
a = np.array([[1,2],[3,4]])
print(np.linalg.det(a))
Output:
-2.0000000000000004

numpy.linalg.solve() function
This function is used to solve a quadratic equation where values can be given in the form of the matrix.
This function is used to solve a quadratic equation where values can be given in the form of the matrix.
The following linear equations
1. X + 2 Y = 8
2. 3X + 4Y = 18
can be represented by using three matrices as:
1 2 𝑥 8
a= [ ] X= [𝑦] b=[ ]
3 4 18
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([[8,18])
print(np.linalg.solve(a, b))
Output:
[2. 3.]

numpy.linalg.inv() function
This function is used to calculate the multiplicative inverse of the input matrix. Consider the following
example.
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]]

By : Dr. Dhaval R. Kher Head of Department [BCA | M.Sc(IT&CA) ] | Dr. Virambhai R. Godhaniya I.T. College, Porbandar. Page | 36

You might also like