0% found this document useful (0 votes)
20 views33 pages

Unit 2 Mca275 PPT Part 2

Uploaded by

PRANAV GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views33 pages

Unit 2 Mca275 PPT Part 2

Uploaded by

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

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

Pandas: Pandas is a Python library used for working with data sets.
 It has functions for analyzing, cleaning, exploring, and manipulating data.
 The name "Pandas" has a reference to both "Panel Data", and "Python
Data Analysis" and was created by Wes McKinney in 2008.
 Pandas is built on top of the NumPy library and is particularly well-suited
for working with tabular data, such as spreadsheets or SQL tables.
 Its versatility and ease of use make it an essential tool for data analysts,
scientists, and engineers working with structured data in Python.
Libraries in Python

What can you do using Pandas?


Pandas are generally used for data science but have you wondered why? This
is because pandas are used in conjunction with other libraries that are used
for data science. It is built on the top of the NumPy library which means that a
lot of structures of NumPy are used or replicated in Pandas. The data
produced by Pandas are often used as input for plotting functions of
Matplotlib, statistical analysis in SciPy, and machine learning algorithms
in Scikit-learn.

A list of things that we can do using Pandas.


 Data set cleaning, merging, and joining.
 Easy handling of missing data (represented as NaN) in floating point as well
as non-floating point data.
 Columns can be inserted and deleted from DataFrame and higher
dimensional objects.
 Powerful group by functionality for performing split-apply-combine
operations on data sets.
Libraries in Python

Installing Pandas
To install the Pandas in our system using the pip command.
type the command:
pip install pandas

Importing Pandas
After the pandas have been installed into the system, you need to import the
library.
This module is generally imported as follows:
import pandas as pd

Pandas Data Structures


Pandas generally provide two data structures for manipulating data, They are:
 Series
 Data Frame
Libraries in Python

Pandas Series:
A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer,
string, float, python objects, etc.).
or
A Pandas Series is like a column in a table. It is a one-dimensional array holding data of any type.
or
Pandas Series is nothing but a column in an Excel sheet.

Creating a Series
In the real world, a Pandas Series will be created by loading the datasets from existing storage,
storage can be SQL Database, CSV file, or an Excel file. Pandas Series can be created from lists,
dictionaries, and from scalar values, etc.
Output:
import pandas as pd
Pandas Series: Series([], dtype: float64)
import numpy as np
Pandas Series:
# Creating empty series 0 s
ser = pd.Series() 1 i
print("Pandas Series: ", ser) 2 n
# simple array 3 g
data = np.array(['s', 'i', 'n', 'g', 'h’]) 4 h
ser = pd.Series(data) dtype: object
Libraries in Python

Create your own labels: Output:


import pandas as pd x 1
y 7
a = [1, 7, 2]
z 2
myvar = pd.Series(a, index = ["x", "y", "z"]) dtype: int64
print(myvar)

Example
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar["y"])

Output:
7
Libraries in Python

Key/Value Objects as Series


You can also use a key/value object, like a dictionary, when creating a Series.

Example
Create a simple Pandas Series from a dictionary:
Output:
import pandas as pd day1 420
calories = {"day1": 420, "day2": 380, "day3": 390} day2 380
myvar = pd.Series(calories) day3 390
print(myvar) dtype: int64
Note: The keys of the dictionary become the labels.
To select only some of the items in the dictionary, use the index argument and
specify only the items you want to include in the Series.

Example Output:
import pandas as pd day1 420
calories = {"day1": 420, "day2": 380, "day3": 390} day2 380
myvar = pd.Series(calories, index = ["day1", "day2"]) dtype: int64
Libraries in Python

Data Frames
Data sets in Pandas are usually multi-dimensional tables, called Data Frames.
 Series is like a column, a Data Frame is the whole table.

Example
Create a DataFrame from two Series:

import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
Output:
myvar = pd.DataFrame(data) calories duration
print(myvar) 0 420 50
1 380 40
2 390 45
Libraries in Python

Pandas provide a unique method to retrieve rows from a Data frame.


DataFrame.loc[] method is a method that takes only index labels and returns row or dataframe.

Pandas use the loc attribute to return one or more specified row(s)
import pandas as pd
data = { Output:
"calories": [420, 380, 390],
"duration": [50, 40, 45]
calories 420
} duration 50
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df.loc[0])

import pandas as pd Output:


data = { calories duration
"calories": [420, 380, 390], 0 420 50
"duration": [50, 40, 45]
1 380 40
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df.loc[[0, 1]])
Libraries in Python

Read CSV Files


 A simple way to store big data sets is to use CSV files (comma
separated files).
 CSV files contains plain text and is a well know format that can be
read by everyone including Pandas

import pandas as pd
df = pd.read_csv('~/Downloads/data12.csv')
print(df.to_string())
Libraries in Python

If you have a large DataFrame with many rows, Pandas will only return
the first 5 rows, and the last 5 rows:
import pandas as pd
df = pd.read_csv('~/Downloads/data12.csv')
print(df)

Analyzing DataFrames
Viewing the Data
 The head() method returns the headers and a specified number of
rows, starting from the top.
Example:
Print the first 5 rows of the DataFrame:
import pandas as pd
df = pd.read_csv('~/Downloads/data12.csv')
print(df.head())
Libraries in Python

Required number of first rows


import pandas as pd
df = pd.read_csv('~/Downloads/data12.csv')
print(df.head(10))

Last rows of DataFrame


 There is also a tail() method for viewing the last rows of the DataFrame.
 The tail() method returns the headers and a specified number of rows,
starting from the bottom.
Examples:
import pandas as pd
df = pd.read_csv('~/Downloads/data12.csv')
print(df.tail())
df['Pulse'].plot()
Libraries in Python

Info About the Data


The DataFrames object has a method called info(), that gives you more
information about the data set.

import pandas as pd
df = pd.read_csv('~/Downloads/data12.csv’)
print(df.info())
Libraries in Python

Matplotlib
 Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
 Matplotlib was created by John D. Hunter. Matplotlib is open source and we can use it
freely.
 Matplotlib is mostly written in python, a few segments are written in C, Objective-C and
Javascript for Platform compatibility.

Installation of Matplotlib
Install it using this command:
 pip install matplotlib
If this command fails, then use a python distribution that already has Matplotlib installed, like
Anaconda, Spyder etc.
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the import module
statement:
 import matplotlib

Now Matplotlib is imported and ready to use:


Libraries in Python

Matplotlib Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt
alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.

Matplotlib Plotting
Plotting x and y points
 The plot() function is used to draw points (markers) in a diagram.

 By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

 Parameter 1 is an array containing the points on the x-axis.

 Parameter 2 is an array containing the points on the y-axis.

If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the plot
function.

import matplotlib.pyplot as plt


import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints)
Libraries in Python

Plotting Without Line


import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()

Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in both
axis.

Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10):

import matplotlib.pyplot as plt


import numpy as np
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()
Libraries in Python

Default X-Points
If we do not specify the points on the x-axis, they will get the default
values 0, 1, 2, 3 etc., depending on the length of the y-points.

Example
Plotting without x-points:

import matplotlib.pyplot as plt


import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()

Note:The x-points in the example above are [0, 1, 2, 3, 4, 5].


Libraries in Python

SciPy
 SciPy stands for Scientific Python.
 SciPy is a scientific computation library that uses NumPy
underneath.
 It provides more utility functions for optimization, stats and signal
processing.
 Like NumPy, SciPy is open source so we can use it freely.
 SciPy was created by NumPy's creator Travis Olliphant.
 SciPy has optimized and added functions that are frequently
used in NumPy and Data Science.
 SciPy is predominantly written in Python, but a few segments
are written in C.
Libraries in Python

Installation of SciPy
pip install scipy
If this command fails, then use a Python distribution that already has
SciPy installed like, Anaconda, Spyder etc.

Import SciPy
Once SciPy is installed, import the SciPy module(s) you want to use in
your applications by adding the from scipy import module statement:

from scipy import constants

Now we have imported the constants module from SciPy, and the
application is ready to use it:
Libraries in Python

Constants in SciPy
As SciPy is more focused on scientific implementations, it provides many built-in
scientific constants.

These constants can be helpful when you are working with Data Science.
 PI is an example of a scientific constant.
Example
Print the constant value of PI:

from scipy import constants


print(constants.pi)

Constant Units
A list of all units under the constants module can be seen using the dir() function.

Example
List all constants:

from scipy import constants


print(dir(constants))
Libraries in Python

Unit Categories
The units are placed under these categories:

Metric
Binary
Mass
Angle
Time
Length
Pressure
Volume
Speed
Temperature
Energy
Power
Force
Libraries in Python

SciPy has many user-friendly, efficient, and easy-to-use functions that


help to solve problems like numerical integration, interpolation,
optimization, linear algebra, and statistics. The benefit of using the
SciPy library in Python while making ML models is that it makes a
strong programming language available for developing fewer complex
programs and applications.
Exception Handling in Python

Errors are the problems in a program due to which the program will
stop the execution.
Error in Python can be of two types i.e.
 Syntax errors
 Exceptions
Syntax Error: As the name suggests this error is caused by the wrong
syntax in the code. It leads to the termination of the program.

Example:
There is a syntax error in the code . The ‘if' statement should be
followed by a colon (:), and the ‘print' statement should be indented to
be inside the ‘if' block.

amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Exception Handling in Python

Exceptions: Exceptions are raised when the program is syntactically


correct, but the code results in an error. This error does not stop the
execution of the program, however, it changes the normal flow of the
program.

Example:
we are dividing the ‘marks’ by zero so a error will occur known as
‘ZeroDivisionError’

marks = 10000
a = marks / 0
print(a)

Note: Exception is the base class for all the exceptions in Python.
Exception Handling in Python

In Python, there are several built-in Python exceptions that can be raised when an
error occurs during the execution of a program. Here are some of the most common
types of exceptions in Python:
 SyntaxError: This exception is raised when the interpreter encounters a syntax
error in the code, such as a misspelled keyword, a missing colon, or an
unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function is applied to
an object of the wrong type, such as adding a string to an integer.
 NameError: This exception is raised when a variable or function name is not
found in the current scope.
 IndexError: This exception is raised when an index is out of range for a list,
tuple, or other sequence types.
 KeyError: This exception is raised when a key is not found in a dictionary.
Exception Handling in Python

 ValueError: This exception is raised when a function or method is called


with an invalid argument or input, such as trying to convert a string to an
integer when the string does not represent a valid integer.
 AttributeError: This exception is raised when an attribute or method is
not found on an object, such as trying to access a non-existent attribute of
a class instance.
 IOError: This exception is raised when an I/O operation, such as reading
or writing a file, fails due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
 ImportError: This exception is raised when an import statement fails to
find or load a module.
Exception Handling in Python
Exception Handling in Python

Exception Handling:
In Python, we use the try...except block to handle exceptions.
try:
The try clause contains the code that can raise an exception, except:
except clause contains the code lines that handle the exception.
Syntax of try...except block:
try:
# code that may cause exception
except:
# code to run when exception occurs
 Every try block is followed by an except block.
 When an exception occurs, it is caught by the except block. The
except block cannot be used without the try block.
Exception Handling in Python
Exception Handling in Python

Example:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
Exception Handling in Python

Handling an exception:
• If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block. After
the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.
Syntax:
try:
You do your operations here;
......................
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Exception Handling in Python

Here are few important points above the above mentioned syntax:
 A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
 You can also provide a generic except clause, which handles any
exception.
 After the except clause(s), you can include an else-clause. The code in the
else-block executes if the code in the try: block does not raise an
exception.
 The else-block is a good place for code that does not need the try: block's
protection.
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 E N G I N E E R I N G

THANK
YOU

You might also like