Unit-2-MCA275-PPT-Part-1

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

SCHOOL OF ENGINEERING &TECHNOLOGY

D E PAR T M E N T O F C O M P U T E R S C I E N C E AN D AP P L I CAT I O N S

Application Programming in Python


Subject Code: MCA-275

Faculty: Dr. Rajneesh Kumar Singh


Assistant Professor
Department of Computer Science
& Applications
Sharda School of Engineering &
Technology, Sharda University
Libraries in Python

Normally, a library is a collection of books or is a room or place where many


books are stored to be used later.

 In the programming world, a library is a collection of precompiled codes that


can be used later on in a program for some specific well-defined operations.

 A Python library is a collection of related modules. It contains bundles of


code that can be used repeatedly in different programs. It makes Python
Programming simpler and convenient for the programmer. As we don’t need
to write the same code again and again for different programs. Python
libraries play a very vital role in fields of Machine Learning, Data Science,
Data Visualization, etc.

 Actually, in the MS Windows environment, the library files have a DLL


extension (Dynamic Link Libraries). When we link a library with our
program and run that program, the linker automatically searches for that
library. It extracts the functionalities of that library and interprets the
program accordingly. That’s how we use the methods of a library in our
program.
Libraries in Python

Python standard library


The Python Standard Library contains the exact syntax, semantics, and tokens of
Python. It contains built-in modules that provide access to basic system
functionality like I/O and some other core modules. Most of the Python
Libraries are written in the C programming language. The Python standard
library consists of more than 200 core modules.

 Numpy: The name “Numpy” stands for “Numerical Python”. It is the


commonly used library. It is a popular machine learning library that supports
large matrices and multi-dimensional data. It consists of in-built
mathematical functions for easy computations. Even libraries like TensorFlow
use Numpy internally to perform several operations on tensors. Array
Interface is one of the key features of this library.
 Pandas: Pandas are an important library for data scientists. It is an open-
source machine learning library that provides flexible high-level data
structures and a variety of analysis tools. It eases data analysis, data
manipulation, and cleaning of data. Pandas support operations like Sorting,
Re-indexing, Iteration, Concatenation, Conversion of data, Visualizations,
Libraries in Python

 Matplotlib: This library is responsible for plotting numerical data.


And that’s why it is used in data analysis. It is also an open-source
library and plots high-defined figures like pie charts, histograms,
scatterplots, graphs, etc.
 SciPy: The name “SciPy” stands for “Scientific Python”. It is an
open-source library used for high-level scientific computations. This
library is built over an extension of Numpy. It works with Numpy to
handle complex computations. While Numpy allows sorting and
indexing of array data, the numerical data code is stored in SciPy. It is
also widely used by application developers and engineers.
 TensorFlow: This library was developed by Google in collaboration
with the Brain Team. It is an open-source library used for high-level
computations. It is also used in machine learning and deep learning
algorithms. It contains a large number of tensor operations.
Researchers also use this Python library to solve complex
computations in Mathematics and Physics.
Libraries in Python

 Scrapy: It is an open-source library that is used for extracting data from websites. It
provides very fast web crawling and high-level screen scraping. It can also be used for
data mining and automated testing of data.
 Scikit-learn: It is a famous Python library to work with complex data. Scikit-learn is an
open-source library that supports machine learning. It supports variously supervised
and unsupervised algorithms like linear regression, classification, clustering, etc. This
library works in association with Numpy and SciPy.
 PyGame: This library provides an easy interface to the Standard Directmedia Library
(SDL) platform-independent graphics, audio, and input libraries. It is used for
developing video games using computer graphics and audio libraries along with Python
programming language.
 PyTorch: PyTorch is the largest machine learning library that optimizes tensor
computations. It has rich APIs to perform tensor computations with strong GPU
acceleration. It also helps to solve application issues related to neural networks.
 PyBrain: The name “PyBrain” stands for Python Based Reinforcement Learning,
Artificial Intelligence, and Neural Networks library. It is an open-source library built
for beginners in the field of Machine Learning. It provides fast and easy-to-use
algorithms for machine learning tasks. It is so flexible and easily understandable and
that’s why is really helpful for developers that are new in research fields.
Libraries in Python

Use of Libraries in Python Program:


In Python, it’s a very simple job to use library due to its easy syntax.
We just need to use import.

4 different ways to import a module in Python


Example:
import math
A = 16
print(math.sqrt(A))
Importing specific items from a library module:
When importing functions, variables, classes, etc., using the from keyword, you can
list multiple items separated by commas.

from math import sqrt, pi


A = 16
pi
print(sqrt(A))
Libraries in Python

Avoiding name collision when importing


If you use the from syntax to grab specific things from a module and you grab
something of the same name from two different modules, you're in for trouble.
Here we're importing sqrt from the math module and sqrt from the cmath module
(cmath is for complex numbers):

>>> from math import sqrt


>>> from cmath import sqrt
To fix this we could rename sqrt from the cmath module as we import it, by using the as
syntax:

>>> from math import sqrt


>>> from cmath import sqrt as csqrt

Example:
>>> sqrt(25)
5.0
>>> csqrt(25)
Libraries in Python

Importing a module under a different name


>>> import math as m
>>> math.pi

The variable m now points to the math module object which means we can't
say math.pi anymore:

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
Instead we can use m.pi or m.sqrt:

>>> m.pi
3.141592653589793
>>> m.sqrt(25)
5.0
Libraries in Python

NumPy stands for numeric python which is a python package for the
computation and processing of the multidimensional and single
dimensional array elements.
Travis Oliphant created NumPy package in 2005 by injecting the features
of the ancestor module Numeric into another module Numarray.
It is an extension module of Python which is mostly written in C. It provides
various functions which are capable of performing the numeric
computations with a high speed.
NumPy provides various powerful data structures, implementing multi-
dimensional arrays and matrices. These data structures are used for the
optimal computations regarding arrays and matrices.

Need of NumPy
NumPy provides a convenient and efficient way to handle the vast amount of
data. NumPy is also very convenient with Matrix multiplication and data
reshaping. NumPy is fast which makes it reasonable to work with a large set
of data.
Libraries in Python

 NumPy aims to provide an array object that is up to 50x faster than


traditional Python lists.

 The array object in NumPy is called ndarray, it provides a lot of


supporting functions that make working with ndarray very easy.

 Arrays are very frequently used in data science, where speed and
resources are very important.

 Data Science: is a branch of computer science where we study how


to store, use and analyze data for deriving information from it.
Libraries in Python

Why is NumPy Faster Than Lists?


NumPy arrays are stored at one continuous place in memory unlike
lists, so processes can access and manipulate them very efficiently.

This behavior is called locality of reference in computer science.

This is the main reason why NumPy is faster than lists. Also it is
optimized to work with latest CPU architectures.

Installation of NumPy
If you have Python and PIP already installed on a system, then
installation of NumPy is very easy.
Install it using this command:

• C:\Users\Your Name>pip install numpy

• If this command fails, then use a python distribution that already


has NumPy installed like, Anaconda, Spyder etc.
Libraries in Python

Advantages of using NumPy for data analysis.


 NumPy performs array-oriented computing.
 It efficiently implements the multidimensional arrays.
 It performs scientific computations.
 It is capable of performing Fourier Transform and reshaping the
data stored in multidimensional arrays.
 NumPy provides the in-built functions for linear algebra and
random number generation.
• Nowadays, NumPy in combination with SciPy and Mat-plotlib is
used as the replacement to MATLAB as Python is more complete
and easier programming language than MATLAB
Libraries in Python

Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output: [1, 2, 3, 4, 5]
Libraries in Python

List of useful NumPy functions


NumPy has numerous useful functions. However, some useful function
are listed below.

Array Creation: arange, array, copy, empty, empty_like, eye, fromfile,


fromfunction, identity, linspace, logspace, mgrid, ogrid, ones,
ones_like, r_, zeros, zeros_like
Conversions: ndarray.astype, atleast_1d, atleast_2d, atleast_3d, mat
Manipulations: array_split, column_stack, concatenate, diagonal,
dsplit, dstack, hsplit, hstack, ndarray.item, newaxis, ravel, repeat,
reshape, resize, squeeze, swapaxes, take, transpose, vsplit, vstack
Questions: all, any, nonzero, where
Libraries in Python

Ordering: argmax, argmin, argsort, max, min, ptp, searchsorted, sort


Operations: choose, compress, cumprod, cumsum, inner, ndarray.fill,
imag, prod, put, putmask, real, sum
Basic Statistics: cov, mean, std, var
Basic Linear Algebra: cross, dot, outer, linalg.svd, vdot

NumPy Creating Arrays


NumPy is used to work with arrays. The array object in NumPy is called
ndarray.
We can create a NumPy ndarray object by using the array() function.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5]) Output:
print(arr) [1 2 3 4 5]
<class 'numpy.ndarray>
print(type(arr))
Libraries in Python

To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray:
Example:
#Use a tuple to create a NumPy array:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Output: [1 2 3 4 5]
Arrays in NumPy:
 It is a table of elements (usually numbers), all of the same type, indexed
by a tuple of positive integers.
 In NumPy, dimensions are called axes. The number of axes is rank.
 NumPy array class is called ndarray. It is also known by the alias array.
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
nested array: are arrays that have arrays as their elements.
Libraries in Python

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D
array.
Example
#Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)

1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Libraries in Python

2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

NumPy has a whole sub module dedicated towards matrix operations called
numpy.mat

Note: use [ ] operators inside numpy.array() for multi-dimensional

Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)

Output:
[[1 2 3]
Libraries in Python

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.

Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)

Output:
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
Libraries in Python

Check Number of Dimensions


NumPy Arrays provides the ndim attribute that returns an integer that
tells us how many dimensions the array have.

Example:
Check how many dimensions the arrays have:

import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]]) output:
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) 0
print(a.ndim) 1
print(b.ndim) 2
print(c.ndim) 3
print(d.ndim)
Libraries in Python

Higher Dimensional Arrays


An array can have any number of dimensions.

When the array is created, you can define the number of dimensions by using
the ndmin argument.

Example
Create an array with 5 dimensions and verify that it has 5 dimensions:

import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)

output:
[[[[[1 2 3 4]]]]]
Libraries in Python

NumPy arrays
The NumPy array - an n-dimensional data structure - is the central object of
the NumPy package.
A one-dimensional NumPy array can be thought of as a vector, a two-
dimensional array as a matrix (i.e., a set of vectors), and a three-dimensional
array as a tensor (i.e., a set of matrices)
Need more than three dimensions?
It's entirely possible to have arrays with many dimensions, including so many
dimensions that it's no longer humanly possible to conceptualize them .
Libraries in Python

Shape of an Array
The shape of an array is the number of elements in each dimension.

Get the Shape of an Array


NumPy arrays have an attribute called shape that returns a tuple with
each index having the number of corresponding elements.
Example:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
Output:
(2, 4)
which means that the array has 2 dimensions, where the first
dimension has 2 elements and the second has 4.
Libraries in Python

Example:
In this example, we are creating a two-dimensional array that has the rank of 2 as it has 2 axes.
The first axis(dimension) is of length 2, i.e., the number of rows, and the second axis(dimension)
is of length 3, i.e., the number of columns. The overall shape of the array can be represented as
(2, 3)

import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
Output:
# Printing type of arr object Array is of type: <class 'numpy.ndarray'>
print("Array is of type: ", type(arr)) No. of dimensions: 2
# Printing array dimensions (axes) Shape of array: (2, 3)
print("No. of dimensions: ", arr.ndim) Size of array: 6
Array stores elements of type: int64
# Printing shape of array
print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array


print("Size of array: ", arr.size)

# Printing type of elements in array


print("Array stores elements of type: ", arr.dtype)
Libraries in Python

Reshaping arrays
Reshaping means changing the shape of an array.

By reshaping we can add or remove dimensions or change number of


elements in each dimension.
Example:
Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements:


import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
output:
newarr = arr.reshape(4, 3) [[ 1 2 3]
print(newarr) [ 4 5 6]
[ 7 8 9]
[10 11 12]]
Libraries in Python

Convert the following 1-D array with 12 elements into a 3-D array.
The outermost dimension will have 2 arrays that contains 3 arrays, each with
2 elements: Output:
import numpy as np [[[ 1 2]
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) [ 3 4]
newarr = arr.reshape(2, 3, 2) [ 5 6]]
print(newarr)

[[ 7 8]
# Reshaping 3X4 array to 2X2X3 array
[ 9 10]
arr = np.array([[1, 2, 3, 4], [11 12]]]
[5, 2, 4, 2],
[1, 2, 0, 1]])

newarr = arr.reshape(2, 2, 3)

print ("Original array:\n", arr)


print("---------------")
Libraries in Python

Operations on a single NumPy array


We can use overloaded arithmetic operators to do element-wise operations on the array to create a new array.
In the case of +=, -=, *= operators, the existing array is modified.

# basic operations on single array Output:


import numpy as np
Adding 1 to every element: [2 3 6 4]
a = np.array([1, 2, 5, 3])
Subtracting 3 from each element: [-2 -
# add 1 to every element
1 2 0]
print ("Adding 1 to every element:", a+1) Multiplying each element by 10: [10 20
# subtract 3 from each element 50 30]
print ("Subtracting 3 from each element:", a-3) Squaring each element: [ 1 4 25 9]
# multiply each element by 10 Doubled each element of original
print ("Multiplying each element by 10:", a*10) array: [ 2 4 10 6]
# square each element
print ("Squaring each element:", a**2) Original array:
# modify existing array [[1 2 3]
a *= 2 [3 4 5]
print ("Doubled each element of original array:", a) [9 6 0]]
Transpose of array:
# transpose of array
[[1 3 9]
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
[2 4 6]
print ("\nOriginal array:\n", a)
[3 5 0]]
Libraries in Python

NumPy – Unary Operators


Many unary operations are provided as a method of ndarray class. This includes sum, min, max, etc.
These functions can also be applied row-wise or column-wise by setting an axis parameter.
# unary operators in numpy
import numpy as np
Output:
arr = np.array([[1, 5, 6],
Largest element is: 9
[4, 7, 2], Row-wise maximum elements: [6 7 9]
[3, 1, 9]]) Column-wise minimum elements: [1 1 2]
# maximum element of array Sum of all array elements: 38
print ("Largest element is:", arr.max()) Cumulative sum along each row:
print ("Row-wise maximum elements:", [[ 1 6 12]
arr.max(axis = 1)) [ 4 11 13]
[ 3 4 13]]
# minimum element of array
print ("Column-wise minimum elements:",
arr.min(axis = 0))
# sum of array elements
print ("Sum of all array elements:",
arr.sum())
# cumulative sum along each row
print ("Cumulative sum along each row:\n",
Libraries in Python

NumPy – Binary Operators


These operations apply to the array elementwise and a new array is created.
You can use all basic arithmetic operators like +, -, /, etc. In the case of +=, -
=, = operators, the existing array is modified.

# Binary operators in Numpy


import numpy as np
a = np.array([[1, 2],
[3, 4]]) Output:
b = np.array([[4, 3], Array sum:
[[5 5]
[2, 1]]) [5 5]]
# add arrays Array multiplication:
print ("Array sum:\n", a + b) [[4 6]
[6 4]]
# multiply arrays (elementwise multiplication)
Matrix multiplication:
print ("Array multiplication:\n", a*b) [[ 8 5]
# matrix multiplication [20 13]]
print ("Matrix multiplication:\n", a.dot(b))
Libraries in Python

Joining NumPy Arrays


Joining means putting contents of two or more arrays in a single array.
In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.
We pass a sequence of arrays that we want to join to the concatenate() function, along with
the axis. If axis is not explicitly passed, it is taken as 0.

Example1:
import numpy as np
Output:
[1 2 3 4 5 6]
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2))
print(arr)

Example2: Output:
import numpy as np [[ 1 2 9 5 6]
arr1 = np.array([[1, 2], [3, 4]]) [ 3 4 12 7 8]]
arr2 = np.array([[5, 6], [7, 8]])
arr = np.concatenate((arr1, arr2), axis=1)
print(arr)
Libraries in Python

Splitting NumPy Arrays:


Splitting is reverse operation of Joining.
Joining merges multiple arrays into one and Splitting breaks one array into multiple.
We use array_split() for splitting arrays, we pass it the array we want to split and the
number of splits.
Example:
import numpy as np Output:
arr = np.array([1, 2, 3, 4, 5, 6]) [array([1, 2]), array([3, 4]), array([5, 6])]
newarr = np.array_split(arr, 3)
print(newarr)

If the array has less elements than required, it will adjust from the end accordingly.
Example
Output:
Split the array in 4 parts:
[array([1, 2]), array([3, 4]), array([5]), array([6])]
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 4)
print(newarr)
Libraries in Python

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
Output:
newarr = np.array_split(arr, 3) [1 2]
print(newarr[0]) [3 4]
[5 6]
print(newarr[1])
print(newarr[2])
Libraries in Python

Searching Arrays:
You can search an array for a certain value, and return the indexes that
get a match.

To search an array, use the where() method.


Example1:
import numpy as np Output:
arr = np.array([1, 2, 3, 4, 5, 4, 4]) (array([3, 5, 6]),)
x = np.where(arr == 4)
print(x)

Example2:
Output:
import numpy as np (array([1, 3, 5, 7]),)
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 0)
Libraries in Python

Sorting Arrays:
Sorting means putting elements in an ordered sequence.

Ordered sequence is any sequence that has an order corresponding to elements,


like numeric or alphabetical, ascending or descending.

The NumPy ndarray object has a function called sort(), that will sort a specified
array. Sorting a 2-D Array
If you use the sort() method on a 2-
Example1: D array, both arrays will be sorted:
import numpy as np
arr = np.array([3, 2, 0, 1]) import numpy as np
print(np.sort(arr)) arr = np.array([[3, 2, 4], [5, 0, 1]])
You can also sort arrays of strings, print(np.sort(arr))
Output:
or any other data type:
[[2 3 4]
Example2:
[0 1 5]]
import numpy as np
Output:
arr = np.array(['banana', 'cherry', 'apple'])
['apple' 'banana' 'cherry']
print(np.sort(arr))

You might also like