Unit 2
Unit 2
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/
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
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:
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
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.
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.
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
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.
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)
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
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.
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.
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)
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
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
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)
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
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
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
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
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
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
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
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.
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
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
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
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]))
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
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]]
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
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