0% found this document useful (0 votes)
5 views97 pages

Python Unit 5

This document provides an overview of creating graphical user interfaces (GUIs) in Python using the Tkinter module, including the structure of a Tkinter program, various widget types, and layout management techniques. It also introduces SQLite, a lightweight database engine, detailing its features, the SQLite3 module, and methods for database operations such as connecting, executing commands, and managing data. The content serves as a guide for beginners to understand and implement GUI applications and database management in Python.

Uploaded by

Kanchan Patil
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)
5 views97 pages

Python Unit 5

This document provides an overview of creating graphical user interfaces (GUIs) in Python using the Tkinter module, including the structure of a Tkinter program, various widget types, and layout management techniques. It also introduces SQLite, a lightweight database engine, detailing its features, the SQLite3 module, and methods for database operations such as connecting, executing commands, and managing data. The content serves as a guide for beginners to understand and implement GUI applications and database management in Python.

Uploaded by

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

UNIT – 5

1. GU Interface
2. Python SQLite
GU Interface:
• The tkinter Module;
• Window and Widgets;
• Layout Management-
pack,
grid and
place.
Python GUI Programming With Tkinter
• Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into
the Python standard library.

• Tkinter has several strengths. It’s cross-platform, so the same code works on
Windows, macOS, and Linux.

• Visual elements are rendered using native operating system elements, so applications
built with Tkinter look like they belong on the platform where they’re run.

• One notable criticism is that GUIs built with Tkinter look outdated. If you want a shiny,
modern interface, then Tkinter may not be what you’re looking for.
Creating a window that contains a single widget.
• The foundational element of a Tkinter GUI is the window.

• Windows are the containers in which all other GUI elements live. These other GUI
elements, such as text boxes, labels, and buttons, are known as widgets.

• Widgets are contained inside of windows.

• The first thing you need to do is import the Python GUI Tkinter module:
Building Your First Python GUI Application With Tkinter
• The first thing you need to do is import the Python GUI Tkinter module:

 import tkinter as tk

• A window is an instance of Tkinter’s Tk class. Create a new window and assign it to the
variable window:

 window = tk.Tk()

• When you execute the code, a new window pops up your screen. How it looks
depends on your operating system.

• Nothing seems to happen, but notice that a new prompt does not appear in the shell.
Building Your First Python GUI Application With Tkinter
• The window.mainloop() tells Python to run the Tkinter event loop.

• This method listens for events, such as button clicks or key-presses, and blocks any
code that comes after it from running until the window it’s called on is closed.

• Go ahead and close the window you’ve created, and you’ll see a new prompt
displayed in the shell.
Structure of a Tkinter Program
import tkinter as tk import tkinter
1

window = tk.Tk() window = tkinter.Tk()

window.mainloop() window.mainloop()
2

from tkinter import *

window = Tk()

window.mainloop() 3
Widget Definition

Widgets: in Tkinter are elements of GUI application, which


provides various controls such as labels, buttons, comboboxes,
checkboxes, menubars, radiobuttons etc., to users to interact
with the application.
Adding a Widget
• Now you have a window, you can add a widget. Use the tk.Label class to add some text to
a window. Create a Label widget with the text "Hello, Tkinter" and assign it to a variable
called greeting:

 greeting = tk.Label(text="Hello, Tkinter")


• You just created a Label widget, but you haven’t added it to the window yet. There are
several ways to add widgets to a window. Right now, you can use
the Label widget’s .pack() method:
 greeting.pack()
• The window now looks like this:
Adding a Widget
• The window now looks like this:

• When you use .pack() a widget into a window, Tkinter sizes the window as small as
it can while still fully encompassing the widget. Now executing the following:
 window.mainloop()

• window.mainloop() tells Python to run the Tkinter event loop. This method listens
for events, such as button clicks or key-presses, and blocks any code that comes
after it from running until the window it’s called on is closed.
1. Label
• It refers to the display box where you can put any text or image which can
be updated any time as per the code.
• The general syntax is:
w=Label(master, option=value)
• master is the parameter used to represent the parent window.
1. Label widget: Example

from tkinter import *

root = Tk()

w = Label(root, text='Welcome to GUI Programming!')


w.pack()

root.mainloop()
2. Button
• Button widget is used to add a button in your application.
• The general syntax is:
w=Button(master, option=value)
• master is the parameter used to represent the parent window.
2. Button widget: Example

from tkinter import *

r = Tk()
r.title('Counting Seconds')

button = Button(r, text='Stop', width=25)


button.pack()

r.mainloop()
3. Checkbutton
• To select any number of options by displaying a number of options to
a user as toggle buttons.
• The general syntax is
w = CheckButton(master, option=value)
• master is the parameter used to represent the parent window.
3. Checkbutton widget: Example
from tkinter import *

master = Tk()

var1 = IntVar()
Checkbutton(master, text='MALE', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='FEMALE', variable=var2).grid(row=1, sticky=W)

master.mainloop()
4. Radiobutton

• It is used to offer multi-choice option to the user. It offers several


options to the user and the user has to choose one option.
The general syntax is;
w = RadioButton(master, option=value)
• master is the parameter used to represent the parent window.
4. Radiobutton widget: Example
from tkinter import *

root = Tk()

v = IntVar()
Radiobutton(root, text='PYTHON', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='JAVA', variable=v, value=2).pack(anchor=W)

root.mainloop()
you can skip this slide during preparation: this is an extra example
from tkinter import *
root = Tk()

w = Label(text = "Select Semester")


w.pack()

radio = IntVar()

R1 = Radiobutton(root,text="1st Sem",variable=radio,value=1)
R2 = Radiobutton(root,text="3rd Sem",variable=radio,value=2)
R3 = Radiobutton(root,text="5th Sem",variable=radio,value=3)

R1.pack()
R2.pack()
R3.pack()

root.mainloop()
5. Entry
• It is used to input the single line text entry from the user.. For multi-
line text input, Text widget is used.
The general syntax is:
w=Entry(master, option=value)
• master is the parameter used to represent the parent window.
5. Entry widget: Example
from tkinter import *

master = Tk()

lb1 = Label(master, text='First Name').grid(row=0)


lb2 = Label(master, text='Last Name').grid(row=1)

e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

master.mainloop()
6. Text
• To edit a multi-line text and format the way it has to be displayed.
The general syntax is:
w =Text(master, option=value)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of
the text.
6. Text widget: Example
from tkinter import *

root = Tk()

T = Text(root, height=2, width=30)


T.pack()
T.insert(END, 'Welcome to GUI Programming\nUsing Tkinter\n')

root.mainloop()
7. Listbox
• It offers a list to the user from which the user can accept any number
of options.
• The general syntax is:
w = Listbox(master, option=value)
• master is the parameter used to represent the parent window.
7. Listbox widget: Example

from tkinter import *

top = Tk()

Lb = Listbox(top)

Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()

top.mainloop()
8. Scale
• It is used to provide a graphical slider that allows to select any value
from that scale.
• The general syntax is:
w = Scale(master, option=value)
master is the parameter used to represent the parent window.
8. Scale widget: Example

from tkinter import *

master = Tk()

w = Scale(master, from_=0, to=50).pack()


w = Scale(master, from_=0, to=200, orient=HORIZONTAL).pack()

mainloop()
9. SpinBox
• It is an entry of ‘Entry’ widget. Here, value can be input by selecting a
fixed value of numbers.
• The general syntax is:
w = SpinBox(master, option=value)
9. Spinbox widget: Example

from tkinter import *

master = Tk()

w = Spinbox(master, from_ = 0, to = 10).pack()

mainloop()
10. Canvas
• The Canvas widget in Tkinter is a versatile widget that allows you to
create and manipulate 2D graphics. It provides a virtual canvas on which
you can draw various shapes and images, as well as add text and other
widgets.
• The general syntax is:
w = Canvas(master, option=value)
10. Canvas widget: Example

from tkinter import *


master = Tk()
w = Canvas(master, width='100',height="100")
w.create_rectangle(10, 20, 90, 80,fill="yellow")
w.pack()
master.mainloop()
Layout managers are also called as geometry managers
• They are used for positioning, arranging and registering widgets on
tkinter window.
• Python provides three layout/ geometry managers.

1. pack()
2. grid()
3. place()
tkinter also offers access to the geometric configuration of the widgets
which can organize the widgets in the parent windows.

There are mainly three geometry manager classes class.


• pack() method: It organizes the widgets in blocks before placing in the
parent widget.

• grid() method: It organizes the widgets in grid (table-like structure) before


placing in the parent widget.

• place() method: It organizes the widgets by placing them on specific


positions directed by the programmer.
1. The pack() method is used to organize widget in the block.

• The widgets added to the python application using the pack() method
can be controlled by using the various options specified in the
method call.
• However, the controls are less and widgets are generally added in the
less organized manner.

• The syntax to use the pack() is given below.

widget.pack(options)
A list of possible options that can be passed in pack() is given below.

• expand: If the expand is set to true, the widget expands to fill any
space.

• Fill: By default, the fill is set to NONE. However, we can set it to X or Y


to determine whether the widget contains any extra space.

• size: it represents the side of the parent to which the widget is to be


placed on the window.
from tkinter import *
parent = Tk(

b1= Button(parent, text = "Red", fg = "red")


b1.pack( side = LEFT)
b2 = Button(parent, text = "Black", fg = "black")
b2.pack( side = RIGHT )
b3 = Button(parent, text = "Blue", fg = "blue")
b3.pack( side = TOP )
b4 = Button(parent, text = "Green", fg = "red")
b4.pack( side = BOTTOM)

parent.mainloop()
2. The grid() geometry manager organizes the widgets in the
tabular form.

• We can specify the rows and columns as the options. We can also
specify the column span (width) or rowspan(height) of a widget.
• This is a more organized way to place the widgets to the python
application.

• The syntax to use the grid() is:


widget.grid(options)
A list of possible options that can be passed inside the grid() method is given
below.

• Column The column number in which the widget is to be placed. The


leftmost column is represented by 0.
• Columnspan The width of the widget. It represents the number of columns
up to which, the column is expanded.
• row The row number in which the widget is to be placed. The topmost row
is represented by 0.
• rowspan The height of the widget, i.e. the number of the row up to which
the widget is expanded.
• Sticky If the cell is larger than a widget, then sticky is used to specify the
position of the widget inside the cell. It may be the concatenation of the
sticky letters representing the position of the widget. It may be N, E, W, S,
NE, NW, NS, EW, ES.
from tkinter import *
parent = Tk()

name = Label(parent,text = "Name").grid(row = 0, column = 0)


e1 = Entry(parent).grid(row = 0, column = 1)

password = Label(parent,text = "Password").grid(row = 1, column = 0)


e2 = Entry(parent, show='*').grid(row = 1, column = 1)

submit = Button(parent, text = "Submit").grid(row = 4, column = 0)

parent.mainloop()
3. The place() geometry manager organizes the widgets to the specific x
and y coordinates.

• The syntax to use the place() is:


widget.place(options)

A list of possible options is given below.

• Anchor: It represents the exact position of the widget within the container.
The default value (direction) is NW (the upper left corner)
• height, width: It refers to the height and width in pixels.
• x, y: It refers to the horizontal and vertical offset in the pixels.
from tkinter import *
top = Tk()
top.geometry("250x170")

name = Label(top, text = "Name").place(x = 30,y = 50)


email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 95, y = 50)
e2 = Entry(top).place(x = 95, y = 90)
e3 = Entry(top).place(x = 95, y = 130)

top.mainloop()
Python SQLite
• The SQLite3 module;
• SQLite Methods- connect, cursor, execute, close;
• Connect to Database;
• Create Table;
• Operations on Tables- Insert, Select, Update, Delete and Drop Records.
Python SQLite
• SQLite is a lightweight, serverless, and self-contained SQL database engine that is
widely used with Python.

• SQLite is a software library that provides a relational database management system


(RDBMS) for embedded and small-scale applications. It is a self-contained,
serverless, zero- configuration, and transactional SQL database engine that is
widely used in various applications such as mobile devices, desktop applications,
and web browsers.

• SQLite is designed to be fast, lightweight, and easy to use, with a small memory
footprint and low CPU usage. It stores data in a single file, making it easy to
distribute and manage, and supports many standard SQL features, such as
transactions, indexes, triggers, and views.

• SQLite is a popular choice for developers who need a local database solution that is
easy to set up and use, and does not require a dedicated server or complex
administration. It is also used as a testing and development database, and as a data
storage format for many applications and operating systems.
Python SQLite3 module
• The SQLite3 module: The sqlite3 module is a built-in module in Python that
provides a simple and easy-to-use interface for working with SQLite
databases. It allows you to create, connect to, and manipulate SQLite
databases using SQL commands.

• To use the sqlite3 module in your Python code, you first need to import it by
adding the following line at the beginning of your code:
import sqlite3 as sq or import sqlite3
Python SQLite methods
SQLite Methods - connect, cursor, execute, close: The sqlite3 module in
Python provides several methods for working with SQLite databases:

Connect to Database:
1. connect:
• connect() method: This method is used to create a connection to an SQLite
database. It takes a single argument - the name of the database file - and
returns a connection object that can be used to execute SQL commands.
• If the database file does not exist, it will be created automatically. Here's an
example:
import sqlite3 as sq
conn = sq.connect('example.db') #Create a connection to the database
Python SQLite methods
Cursor Object and its methods: A cursor object is used to interact with a
database. A cursor is created by a database connection object, and it is used to
execute SQL statements and retrieve data from the database.
2. cursor() method: This method is used to create a cursor object that can be
used to execute SQL commands. It is called on a connection object and returns
a cursor object. Here's an example:
# Create a cursor object
cur = conn.cursor()

3. execute() method: This method is used to execute an SQL command. It takes


a single argument - the SQL command - and returns a cursor object that can be
used to fetch the results. Here's an example:
# Execute a query
cur.execute(‘create table person(id integer, name text)’)
Python SQLite methods
4. fetchone() method: This method is used to fetch the next row of a query
result set. It returns a tuple of values or None if there are no more rows to
fetch. Here's an example:
# Fetch the next row
row = cur.fetchone()

5. fetchall() method: This method is used to fetch all the rows of a query result
set. It returns a list of tuples of values. Here's an example:
# Fetch all the rows
rows = cur.fetchall()
Python SQLite methods
6. commit() method: This method is used to save the changes made to the
database. It is called on a connection object and commits the current
transaction. Here's an example:
# Commit the changes
conn.commit()

7. close() method: This method is used to close the cursor and the connection.
It is called on both the cursor object and the connection object. Here's an
example:
# Close the cursor and the connection
cur.close()
conn.close()
Operations on tables: create, insert, select, update, delete and drop records.
import sqlite3 as sq
# create a connection to a SQLite database
conn = sq.connect('employee.db')
# create a cursor object
cur = conn.cursor()
# create a table
cur.execute("CREATE TABLE employee (id INTEGER, name TEXT)")
# insert a record in to the table
cur.execute("INSERT INTO employee (id, name) VALUES (101, 'Ravi')")
cur.execute("INSERT INTO employee(id, name) VALUES (102, 'Ravishankar')")
cur.execute("INSERT INTO employee (id, name) VALUES (103, 'Ramesh')")
# select records from the table
cur.execute("SELECT * FROM employee")
rows = cur.fetchall()
for row in rows:
print(row)
# update a record in the table
cur.execute("update employee set name ='Rakesh' where id = 101")
# delete a record from the table
cur.execute("delete from employee where id = 103")
# drop the table
cur.execute("DROP TABLE employee")
# commit the transaction
conn.commit()
# close the cursor and the connection
cur.close()
conn.close()
STEPS IN DATABASE
1. Import sqlite3 package in python file
import sqlite3
2. Connect with database/sql
conn = connect(“dbfile.db”)
3. Create a cursor object
cur = conn.cursor()
STEPS IN DATABASE
4. Execute sql queries
cursor.execute()
5. Close the connection
con.close()
Program To Check Database Connection:
This program is written to connect to database;
import sqlite3

db = sqlite3.connect("College.db")
print(db)

if(db):
print("Connection is successfull")
else:
print("Connection unsuccessfull")
5
UNIT –
3. DATA ANALYSIS
&
4. DATA VISUALISATION
DATA ANALYSIS
NumPy
• Introduction to NumPy,
• Array Creation using NumPy,
• Operations on Arrays;

Pandas
• Introduction to Pandas,
• Series and DataFrames,
• Creating DataFrames from Excel Sheet and .csv file,
• Dictionary and Tuples.
• Operations on DataFrames.
NumPy
• NumPy is a powerful Python library for numerical computing that is widely
used in data analysis.
• It provides efficient implementations of many mathematical functions and
operations on large arrays and matrices.
• Here are some of the key features of NumPy:

1. Multi-Dimensional Arrays:
• NumPy provides a powerful ndarray class for representing multi-
dimensional arrays. These arrays can have any number of dimensions, and
can be indexed and sliced in various ways.
NumPy
2. Mathematical Operations:
• NumPy provides many built-in functions for performing mathematical
operations on arrays. These functions are optimized for efficiency and can
handle large arrays with ease.
• Some examples include np.add(), np.subtract(), np.multiply(), np.divide(),
np.power(), np.sqrt(), and more.

3. Linear Algebra:
• NumPy provides a range of functions for linear algebra operations, including
matrix multiplication, determinant calculation, eigenvalue and eigenvector
calculation, and more. These functions are optimized for performance and
can handle large matrices efficiently.
NumPy
4. Random Number Generation:
• NumPy provides functions for generating random numbers from various
probability distributions. These functions are useful for many statistical and
simulation tasks.

5. Broadcasting:
• NumPy provides a powerful broadcasting feature that allows arrays with
different shapes to be used in arithmetic operations. This can simplify many
calculations and make them more efficient.
Array Creation using NumPy:

• NumPy provides several ways to create arrays in Python. Here are some of
the most common ways to create arrays using NumPy:

1: np.array(): This function creates an array from a python list or tuple.


Example:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a) # [1 2 3 4 5]
b = np.array((1, 2 3))
print(b) # [1 2 3]
Array Creation using NumPy:
2: np.zeros(): This function creates an array filled with zeros.
Example:
import numpy as np
a = np.zeros(5)
print(a) # [0. 0. 0. 0. 0.]
b = np.zeros((2, 3))
print(b) # [[0. 0. 0.]
[0. 0. 0.]]
Array Creation using NumPy:
3: np.arange(): This function creates an array with a range of values.
Example:
import numpy as np
a = np.arange(1, 6)
print(a) # [1, 2, 3, 4, 5]
b = np.arange(0, 1, 0.2)
print(b) # [0. 0.2 0.4 0.6 0.8]
b = np.arange(1, 11, 2)
print(c) # [1, 3, 5, 7, 9]
Operations on Arrays:
NumPy is a Python library that provides support for large, multi- dimensional arrays
and matrices, along with a range of mathematical functions to operate on them
efficiently.

Here are some of the commonly used operations on arrays using NumPy:
1. add() operation / addition
2. array indexing
3. array slicing
4. reshape()
5. concatenate()
6. transpose()
7. mean()
8. sort()
Operations on Arrays:
1: add() operation and addition: to add two arrays element-wise, you can use
the numpy.add() function
Example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.add(a,b)
print(c) # [5, 7, 9]
Operations on Arrays:
2: array indexing: You can access elements of an array using indexing. For
example, to access the element at index 2 of an array, you can use array [2].

3. array slicing: Array slicing is a technique used to extract a subset of elements


from an array in Python. It is a way to create a new array by selecting a part of
an existing array.
Example:
import numpy as np
a = np.array([1, 2, 3, 4, 5]) # Create a 1-dimensional array
b = a[1:3] # Slice the array from index 1 to index 3
print(b) # Output: [2 3]
Operations on Arrays:
4: array reshape: You can reshape an array using the numpy.reshape() function.
For example, to reshape a 1-dimensional array to a 2-dimensional array with 2
rows and 3 columns, you can use:

Ex:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
new_arr =arr.reshape((2, 3))
print(new_arr) # Output: [[1 2 3]
[4 5 6]]
Operations on Arrays:
5. concatenate(): You can concatenate two or more arrays using the
numpy.concatenate() function. For example, to concatenate two arrays a and b
vertically, you can use:

import numpy as np
a = np.array([[1, 2], [3, 4]]
b = np.array([5, 6])
c = np.concatenate((a, b), axis=0)
print(c) # Output: [[1 2]
[3 4 ]
[5 6]]
Operations on Arrays:
6. transpose (): You can transpose an array using the numpy.transpose()
function. For example, to transpose a 2-dimensional array, you can use:

import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
new_arr = np.transpose(arr)
print(new_arr) # Output: [[1, 3, 5]
[2, 4, 6]]
Operations on Arrays:
7. mean (): 8. sort():
You can perform statistical You can sort the elements of an array
operations on arrays using NumPy. using the numpy.sort() function.
For example, to calculate the mean For example, to sort the elements of
of an array arr,
an array arr in ascending order, you
Ex: can use:
import numpy as np Ex: import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr =np.array([3, 1, 4, 2, 5])
mean = np.mean(arr) sorted_arr = np.sort(arr)
print(mean) print(sorted _arr)

# Output: 3.0
# Output: [1 2 3 4 5]
Operations on Arrays:
9. broadcasting(): NumPy provides broadcasting, which is a powerful
mechanism that allows you to perform arithmetic operations between arrays
with different shapes.
For example, to add a scalar value to an array arr, you can use:
Ex:
import numpy as np
arr = np.array([1, 2, 3])
new_arr = arr + 1
print(new_arr) # Output: [2 3 4]
DATA ANALYSIS
NumPy
• Introduction to NumPy,
• Array Creation using NumPy,
• Operations on Arrays;

Pandas
• Introduction to Pandas,
• Series and DataFrames,
• Creating DataFrames from Excel Sheet and .csv file,
• Dictionary and Tuples.
• Operations on DataFrames.
Pandas
Introduction to Pandas:
• Pandas is a popular open-source data analysis and manipulation library in
Python.
• It provides easy-to-use data structures and data analysis tools for handling
and manipulating numerical tables and time-series data.
• Pandas is built on top of NumPy, which makes it fast and efficient for
working with large datasets.

• Series and DataFrames.


Pandas Series and DataFrames:
The two primary data structures used in Pandas are Series and DataFrame.

• Series: A one-dimensional array-like object that can hold data of any type. It
consists of a sequence of values and an associated array of labels, which is
called the index. The index can be of any type, including integers, strings, or
dates.

• DataFrame: A two-dimensional table-like data structure that consists of


rows and columns. It is similar to a spreadsheet or a SQL table. Each column
in a DataFrame can have a different data type, such as integer, float, or
string. A DataFrame can also have row labels and column labels.
Pandas
Pandas provides many tools for data analysis and manipulation, including:

• Data filtering, selection, and manipulation


• Data aggregation and grouping
• Handling missing data
• Merging and joining datasets
• Reshaping and pivoting data
• Time-series analysis and manipulation
Creating dataframes
import pandas as pd
# Create a DataFrame from a dictionary

data = {'name': ['Alice', 'Bob', 'Charlie', 'Dave'],


'age': [25, 32, 18, 47],
'city': ['New York', 'Paris', 'London', 'San Francisco']}
df = pd.DataFrame(data)
Output:
print(df) name age city
0 Alice 25 New York
1 Bob 32 Paris
2 Charlie 18 London
3 Dave 47 San Francisco
Creating DataFrames from Excel sheet and .csv files,
Dictionary and Tuples
import pandas as pd

# Read data from multiple sheets in an Excel file


data = pd.read_excel('person_emp.xlsx', sheet_name=['person'])

# Create DataFrames from the data


df1 = data['person']

# Print the DataFrames print(df1) Unnamed: 0 NAME AGE


print(df1) 0 0 ravi 25
1 1 raju 22
2 2 rakesh 21
Creating DataFrames from dictionary
You can create a Pandas DataFrame from a dictionary in Python by using the pd.DataFrame()
constructor. The dictionary keys become the column names, and the dictionary values become
the column values. Here's an example:
import pandas as pd

# Create a dictionary of data


data = {'regno': [1,2,3],'name':['ramesh', 'suresh', 'rajesh']}

# Create a DataFrame from the dictionary


df = pd.DataFrame(data)
regno name
0 1 ramesh
# Print the DataFrame 1 2 suresh
print(df) 2 3 raju
Creating DataFrames from tuple
You can create a Pandas DataFrame from a list of tuples in Python by using the pd.DataFrame
constructor. Each tuple in the list represents a row in the DataFrame. Here's an example:
import pandas as pd

# Create a list of tuples


data= [('Rajesh', 25, 'New York'), ('Ramesh', 32, 'Paris')]

# Create a DataFrame from the list of tuples


df = pd.DataFrame(data, columns= ['name', 'age', 'city'])
name age city
# Print the DataFrame 0 Rajesh 25 New York
1 Ramesh 32 Paris
print(df)
Operations on DataFrames
1. Selecting Columns
2. Filtering Rows
3. Sorting
4. Aggregation
5. Grouping
6. Joining
7. Reshaping
Operations on DataFrames
Selecting Columns: You can select one or more columns from a DataFrame using indexing. For
example, df[‘column_name’] selects a single column, and df[['column_1', 'column_2‘]]
selects multiple columns.

Filtering Rows: You can filter rows of a DataFrame using boolean indexing. For example,
df[df['column_name'] >10] filters rows where the value in column_name is greater than 10.

Sorting: You can sort a DataFrame by one or more columns using the sort_values() method.
For example, df.sort_values(by='column_name') sorts the DataFrame by column_name.
Operations on DataFrames
Aggregation: You can compute summary statistics of a DataFrame using the agg() method. For
example, df.agg({'column_name': 'mean'}) computes the mean of column_name.

Grouping: You can group a DataFrame by one or more columns using the groupby() method.
For example, df.groupby('column_name').agg({column_2': 'mean’}) groups the DataFrame by
column_name and computes the mean of column_2 for each group.
Operations on DataFrames
Joining: You can join two or more DataFrames using the merge() method. For example,
pd.merge(df1, df2, on='column_name') joins df1 and df2 on column_name.

Reshaping: You can reshape a DataFrame using the pivot() method. For example,
df.pivot(index='column_1', columns='column 2,' values='column 3') pivots the DataFrame so
that column_1 becomes the index, column_2 becomes the columns, and column_3 becomes
the values.
DATA VISUALISATION
DATA VISUALISATION
• Introduction to Data Visualisation;
• Matplotlib Library;
• Different Types of Charts using Pyplot:
• Line chart,
• Bar chart
• Histogram and
• Pie chart.
DATA VISUALISATION
• Data visualization is the process of representing data in a visual format, such
as charts, graphs, and maps, to help identify patterns, trends, and
relationships within the data.

• In Python, there are several libraries available for data visualization, such as
Matplotlib, Seaborn, Plotly, etc.
Introduction to Data Visualisation
• Data visualization can be used for exploratory data analysis, to better
understand the data and identify interesting patterns and relationships.

• It can also be used for data communication, to effectively convey insights


and findings to stakeholders.

• Python's data visualization libraries provide a wide range of customizable


and interactive plots and charts that can be used to visualize different types
of data, such as numerical, categorical, and time-series data. These libraries
provide a high level of flexibility and customization, allowing users to create
publication-quality visualizations.

• Some common types of plots that can be created in Python include line
plots, scatter plots, bar plots, histograms, heatmaps, and more.
Matplotlib Library
• Matplotlib is a plotting library in Python that is widely used for creating
static, interactive, and publication-quality visualizations. It provides a wide
range of plots, including line plots, scatter plots, bar plots, histograms, and
more.

• Different Types of Charts using Pyplot- Line chart, Bar chart and Histogram
and Pie chart.

• Matplotlib's pyplot module provides a wide range of charts and plots that
can be used for data visualization. Here are some of the most commonly
used types of charts: Line Chart, Bar Chart, Pie chart and Histogram
Matplotlib Library
1. Line Chart: A line chart is used to plot a series of data points connected by
straight lines. It is useful for visualizing trends and changes over time.

2. Bar Chart: A bar chart is used to compare values between different


categories. It is useful for visualizing categorical data, such as the number
of students in different grades.

3. Pie Chart: A pie chart is used to show the proportion of different categories
in a dataset. It is useful for visualizing percentages and proportions.

4. Histogram: A histogram is used to show the distribution of a dataset. It is


useful for visualizing the frequency of data values.
1. Line chart: Example
• Line chart: In this example, we first import the pyplot module from the
matplotlib library.

• We then define the x and y data arrays, which represent the x and y values of
the data points in the line chart. Also we use plt.plot() method to create line
chart.
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [3, 2, 4, 1, 5]

# Create line chart


plt.plot(x, y)

# Add labels and title


plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title ('Line chart example')

plt.show()
2. Bar chart: Example
• In this example, we first import the pyplot module from the matplotlib library.
We then define the x and y data arrays, which represent the categories and
values for the bar chart.

• Next, we use the plt.bar() function to create a vertical bar chart. The plt.bar()
function takes the x and y data arrays as arguments and creates a bar chart
with the categories on the x- axis and the values on the y-axis.
import matplotlib.pyplot as plt
# Sample data
x = ['A', 'B', 'C', 'D', 'E']
y = [3, 7, 2, 5, 9]
# Create vertical bar chart
plt. bar(x, y)
# Add labels and title
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label"')
plt. title ('Vertical bar chart example')
# Show the plot
plt.show()
3. Pie chart: Example
• In this example, we first import the pyplot module from the matplotlib library.
We then define the sizes and labels lists, which represent the sizes and labels
of the pie chart slices.

• Next, we use the plt.pie() function to create a pie chart. The plt.pie() function
takes the sizes and labels lists as arguments and creates a pie chart with the
slices labeled with the labels.
import matplotlib.pyplot as plt

# Sample data
sizes = [30, 25, 20, 15, 10]
labels= ['A', 'B', 'C', 'D', 'E']

# Create pie chart


plt.pie(sizes, labels=labels)

# Add title
plt.title('Pie chart example')

# Show the plot


plt.show()
4. Histogram: Example
• In this example, we first import the pyplot module from the matplotlib library
and the numpy library for generating random sample data.

• Next, we use the plt.hist() function to create a histogram chart. The plt.hist()
function takes the data array as an argument and creates a histogram chart
with 20 bins by default.

• [bins – the towers or bars of a histogram are called bins]


import matplotlib.pyplot as pt

data = [1,2,2,3,6,6,2,2,1,1,4,4,5,5,6,1,2,2]

pt.hist(data, bins=5)

pt.title("Histogram")
pt.xlabel("value")
pt.ylabel("Frequency")

pt.show()

You might also like