0% found this document useful (0 votes)
37 views

Unit - 5 Python

Notes

Uploaded by

bipruu
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)
37 views

Unit - 5 Python

Notes

Uploaded by

bipruu
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/ 45

UNIT-5

GU-INTERFACE
Python Tkinter:
Python provides the standard library Tkinter for creating the graphical user
interface for desktop-based applications.

Developing desktop-based applications with python Tkinter is not a


complex task. An empty Tkinter top-level window can be created by using
the following steps.

➢ import the Tkinter module.


➢ Create the main application window.
➢ Add the widgets like labels, buttons, frames, etc. to the window.
➢ Call the main event loop so that the actions can take place on the user's
computer screen.

Example

from tkinter import *


#creating the application main window.
top = Tk()
#Entering the event main loop
top.mainloop()
Output:
Python Tkinter Geometry or layout
management
The Tkinter geometry specifies the method by using which, the widgets are
represented on display. The python Tkinter provides the following geometry
or layout management methods.

1. The pack() method


2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method:

The pack() widget is used to organize widget in the block. The positions
widgets added to the python application using the pack() method can be
controlled by using the various options specified in the method call.

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


syntax
widget.pack(options)

Example

from tkinter import *


parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()

Output:
Python Tkinter grid() method
The grid() geometry manager organizes the widgets in the tabular form.
We can specify the rows and columns as the options in the method call. 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 given below.

Syntax
widget.grid(options)

A list of possible options that can be passed inside the grid() method is
given below.
o Column
The column number in which the widget is to be placed. The leftmost
column is represented by 0.
o Columnspan
The width of the widget. It represents the number of columns up to
which, the column is expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's
border.
o padx, pady
It represents the number of pixels to pad the widget outside the
widget's border.
o row
The row number in which the widget is to be placed. The topmost row
is represented by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the
widget is expanded.
o 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.
Example

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).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()

Output:

Python Tkinter place() method


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

Syntax
widget.place(options)
Example
from tkinter import *
top = Tk()
top.geometry("400x250")
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 = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()

Output:

Tkinter widgets

In general, Widget is an element of Graphical User Interface (GUI) that


displays/illustrates information or gives a way for the user to interact
with the OS. In Tkinter , Widgets are objects ; instances of classes
that represent buttons, frames, and so on.
Each separate widget is a Python object. When creating a widget, you
must pass its parent as a parameter to the widget creation function. The
only exception is the “root” window, which is the top-level window that
will contain everything else and it does not have a parent.

There are various widgets like button, canvas, checkbutton, entry, etc. that
are used to build the python GUI applications.

SN Widget Description

1 Button The Button is used to add various kinds of buttons


to the python application.

2 Canvas The canvas widget is used to draw the canvas on


the window.
3 Checkbutton The Checkbutton is used to display the
CheckButton on the window.

4 Entry The entry widget is used to display the single-line


text field to the user. It is commonly used to accept
user values.

5 Frame It can be defined as a container to which, another


widget can be added and organized.

6 Label A label is a text used to display some message or


information about the other widgets.

7 ListBox The ListBox widget is used to display a list of


options to the user.

8 Menubutton The Menubutton is used to display the menu items


to the user.

9 Menu It is used to add menu items to the user.

10 Message The Message widget is used to display the


message-box to the user.

11 Radiobutton The Radiobutton is different from a checkbutton.


Here, the user is provided with various options and
the user can select only one option among them.

12 Scale It is used to provide the slider to the user.

13 Scrollbar It provides the scrollbar to the user so that the user


can scroll the window up and down.

14 Text It is different from Entry because it provides a


multi-line text field to the user so that the user can
write the text and edit the text inside it.

14 Toplevel It is used to create a separate window container.


15 Spinbox It is an entry widget used to select from options of
values.

16 PanedWindow It is like a container widget that contains horizontal


or vertical panes.

17 LabelFrame A LabelFrame is a container widget that acts as the


container

18 MessageBox This module is used to display the message-box in


the desktop based applications.

Python Tkinter Canvas


The canvas widget is used to add the structured graphics to the python
application. It is used to draw the graph and plots to the python application.
The syntax to use the canvas is given below.

Syntax
1. w = canvas(parent, options)

Example

from tkinter import *

top = Tk()
top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200")
c.pack()
top.mainloop()

Output:
Python Tkinter Button
The button widget is used to add various types of buttons to the python
application. Python allows us to configure the look of the button according
to our requirements. Various options can be set or reset depending upon
the requirements.

Button is used to perform particular task.

We can also associate a method or function with a button which is called


when the button is pressed.

The syntax to use the button widget is given below.

Syntax
W = Button(parent, options)

Example1
#python application to create a simple button

from tkinter import *


top = Tk()
top.geometry("200x100")
b = Button(top,text = "Simple")
b.pack()
p.mainaloop()

Output:
Example2:

Python Tkinter Checkbutton


The Checkbutton is used to track the user's choices provided to the
application. In other words, we can say that Checkbutton is used to
implement the on/off selections.

The Checkbutton can contain the text or images. The Checkbutton is mostly
used to provide many choices to the user among which, the user needs to
choose the one. It generally implements many of many selections.

The syntax to use the checkbutton is given below.


Syntax

w = checkbutton(master, options)

Example
from tkinter import *

top = Tk()

top.geometry("200x200")

checkvar1 = IntVar()

checkvar2 = IntVar()

checkvar3 = IntVar()

chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue =


1, offvalue = 0, height = 2, width = 10)

chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2, onvalue


= 1, offvalue = 0, height = 2, width = 10)

chkbtn3 = Checkbutton(top, text = "Java", variable = checkvar3, onvalue


= 1, offvalue = 0, height = 2, width = 10)

chkbtn1.pack()

chkbtn2.pack()

chkbtn3.pack()

top.mainloop()

Output:
Another example:

Python Tkinter Entry


The Entry widget is used to provde the single line text-box to the user to
accept a value from the user. We can use the Entry widget to accept the
text strings from the user. It can only be used for one line of text from the
user. For multiple lines of text, we must use the text widget.

The syntax to use the Entry widget is given below.

Syntax
w = Entry (parent, options)

A list of possible options is given below.

SN Option Description
1 Bg The background color of the widget.

2 Bd The border width of the widget in pixels.

3 Cursor The mouse pointer will be changed to the


cursor type set to the arrow, dot, etc.

4 Exportselection The text written inside the entry box will be


automatically copied to the clipboard by
default. We can set the exportselection to 0
to not copy this.

5 Fg It represents the color of the text.

6 Font It represents the font type of the text.

7 Highlightbackground It represents the color to display in the


traversal highlight region when the widget
does not have the input focus.

8 Highlightcolor It represents the color to use for the


traversal highlight rectangle that is drawn
around the widget when it has the input
focus.

Example
from tkinter import *
top = Tk()
top.geometry("400x250")
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)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", active
foreground = "blue").place(x = 30, y = 170)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()

Output:
Python Tkinter Label
The Label is used to specify the container box where we can place the text
or images. This widget is used to provide the message to the user about
other widgets used in the python application.

There are the various options which can be specified to configure the text
or the part of the text shown in the Label.

The syntax to use the Label is given below.

Syntax
w = Label (master, options)

SN Option Description

1 anchor It specifies the exact position of the text within the size
provided to the widget. The default value is CENTER,
which is used to center the text within the specified
space.

2 bg The background color displayed behind the widget.

3 bitmap It is used to set the bitmap to the graphical object


specified so that, the label can represent the graphics
instead of text.
4 bd It represents the width of the border. The default is 2
pixels.

5 cursor The mouse pointer will be changed to the type of the


cursor specified, i.e., arrow, dot, etc.

6 font The font type of the text written inside the widget.

7 fg The foreground color of the text written inside the


widget.

8 height The height of the widget.

9 image The image that is to be shown as the label.

Example

from tkinter import *


top = Tk()
top.geometry("400x250")

#creating label
uname = Label(top, text = "Username").place(x = 30,y = 50)

#creating label
password = Label(top, text = "Password").place(x = 30, y = 90)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", active
foreground = "blue").place(x = 30, y = 120)
e1 = Entry(top,width = 20).place(x = 100, y = 50)
e2 = Entry(top, width = 20).place(x = 100, y = 90)
top.mainloop()

Output:
Python Tkinter Listbox
The Listbox widget is used to display the list items to the user. We can
place only text items in the Listbox and all text items contain the same font
and color.

The user can choose one or more items from the list depending upon the
configuration.

The syntax to use the Listbox is given below.

1. w = Listbox(parent, options)

A list of possible options is given below.

SN Option Description

1 bg The background color of the widget.

2 bd It represents the size of the border. Default value


is 2 pixel.

3 cursor The mouse pointer will look like the cursor type like
dot, arrow, etc.

4 font The font type of the Listbox items.

5 fg The color of the text.

6 height It represents the count of the lines shown in the


Listbox. The default value is 10.

7 highlightcolor The color of the Listbox items when the widget is


under focus.

Example
from tkinter import *

top = Tk()

top.geometry("200x250")
lbl = Label(top,text = "A list of favourite countries...")

listbox = Listbox(top)

listbox.insert(1,"India")

listbox.insert(2, "USA")

listbox.insert(3, "Japan")

listbox.insert(4, "Austrelia")

lbl.pack()
listbox.pack()

top.mainloop()

Output:
SQLite3
What is SQLite
SQLite is embedded relational database management system. It is self-
contained, serverless, zero configuration and transactional SQL database
engine.

SQLite is different from other SQL databases because unlike most other SQL
databases, SQLite does not have a separate server process. It reads and writes
directly to ordinary disk files. A complete SQL database with multiple tables,
indices, triggers, and views, is contained in a single disk file.

There are several reasons why you might choose to use SQLite in
your project:
1. Ease of use: SQLite is very easy to get started with, as it
requires no setup or configuration. You can simply include
the library in your project and start using it.
2. Embeddability: SQLite is designed to be embedded into
other applications. It is a self-contained, serverless
database engine, which means you can include it in your
application without the need for a separate database
server.
3. Lightweight: SQLite is a very lightweight database
engine, with a small library size (typically less than 1MB).
This makes it well-suited for use in applications where the
database is embedded directly into the application binary,
such as mobile apps.
4. Serverless: As mentioned earlier, SQLite is a serverless
database engine, which means there is no need to set up
and maintain a separate database server process. This
makes it easy to deploy and manage, as there are no
additional dependencies to worry about.
5. Cross-platform: SQLite is available on many platforms,
including Linux, macOS, and Windows, making it a good
choice for cross-platform development.
6. Standalone: SQLite stores all of the data in a single file on
the filesystem, which makes it easy to copy or backup the
database.
7. High reliability: SQLite has been widely tested and used
in production systems for many years, and has a
reputation for being a reliable and robust database engine.
Connect SQLite3 with Python

First you have to install Python and SQLite3 on your system.

Sqlite3 Installation on Windows:


If you want to install the official SQLite binary and interact with the
database using the terminal, you can follow these directions:
1. Visit the official website of SQLite to download the zip file.
2. Download that zip file.
3. Create a folder in C or D ( wherever you want ) for storing
SQLite3 by expanding the zip file.
4. Open the advanced system settings and select the environt
variable→system variable→path→ then select new path and paste
the path where sqlite3 is stored example:\sqlite
After installation import sqlite3 and perform as you need

SQLite Methods
➢ Connect method
➢ Cursor method
➢ Execute method
➢ Close method

Connect method:
Connect method is used to connect with the database if database is
already created otherwise, it will create the new database.
Syntax:
Connection string = sqlite3.connect(‘databasename.db’)

Example:
Conn=sqlite3.connect(‘mydatabase.db’)

New database (mydatabase) is created.


Cursor method or object:

It is an object that is used to make the connection for executing


SQL queries. It acts as middleware between SQLite database
connection and SQL query. It is created after giving connection to
SQLite database.
Syntax:
cursor_object=connection_object.execute(“sql query”);

Example:
# create a cousor object for select query
cursor = connection.execute("SELECT * from student ")

# display all data from hotel table


for row in cursor:
print(row)

Execute method:

In order to execute an SQLite script or query in python, we will use


the execute() method with connect() object:

Syntax:
connection_object.execute(“sql statement”)
Example:
Conn.execute(“create table student(name char,regnumber int)”)

Close method:
Close method is used to close the database connection once the process
is done with database.

Syntax:
Connection_object.close()

Example:
Conn.close()
SQLite Commands
SQLite commands are similar to SQL commands. There are three types of
SQLite commands:

o DDL: Data Definition Language


o DML: Data Manipulation Language
o DQL: Data Query Language

Data Definition Language


There are three commands in this group:

CREATE: This command is used to create a table, a view of a table or other


object in the database.

ALTER: It is used to modify an existing database object like a table.

DROP: The DROP command is used to delete an entire table, a view of a


table or other object in the database.

Data Manipulation language


There are three commands in data manipulation language group:

INSERT: This command is used to create a record.

UPDATE: It is used to modify the records.

DELETE: It is used to delete records.

Data Query Language


SELECT: This command is used to retrieve certain records from one or
more table.

How to create database in sqlite3


Create a python file "connect.py", having the following code:

import sqlite3

conn = sqlite3.connect('mydatabase.db')

print("Opened database successfully")


(Database is created successfully)

Create a table
Create a table "student" within the database "mydatabase".

Create a python file "createtable.py", having the following code:

import sqlite3

conn = sqlite3.connect('mydatabase.db')
print ("Opened database successfully")

conn.execute(‘’’create table student(regno int primary key,name


varchar(20),class varchar(10))’’’)
print ("Table created successfully” )

conn.close()

Insert Records
Insert some records in "student" table.

Create a python file "connection.py", having the following code:

import sqlite3

conn = sqlite3.connect('mydatabase.db')
print("Opened database successfully")
conn.execute("insert into student values(1001,'Lavanya','Msc')")
conn.execute("insert into student values(1002,'Saritha', 'MA')")
conn.execute("insert into student values(1003,'Meena', 'Msc')")
print("three rows inserted successfully")
conn.commit()
conn.close()

Display the records of student database

import sqlite3
conn=sqlite3.connect('mydatabase.db')
print("Database opened")

c= conn.execute("select * from student")


# display all data from student table
for r in c:
print(r)
conn.close()

Output:
Database opened
(1001, 'Lavanya', 'Msc')
(1002, 'Saritha', 'MA')
(1003, 'Meena', 'Msc')

Upadate command in sqlite3

import sqlite3
conn=sqlite3.connect('mydatabase.db')
print("opened")
conn.execute("update student set class='MCA' where name='Lavanya'")

c= conn.execute("select * from std")

# display all data from student table


for r in c:
print(r)
conn.commit()
conn.close()

Output:
Database opened
(1001, 'Lavanya', 'MCA')
(1002, 'Saritha', 'MA')
(1003, 'Meena', 'Msc')

Data Analysis

Numpy package in python:


NumPy stands for numeric python which is a python package or library for
the computation and processing of the multidimensional and single
dimensional array elements.

NumPy Environment Setup


NumPy doesn't come bundled with Python. We have to install it using the
python pip installer. Execute the following command in command prompt.

pip install numpy

Example:
C:\Users\lavanya>pip install numpy

Why Use NumPy?


In Python we have lists that serve the purpose of arrays, but they are
slow to process.

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.

There are the following advantages of using NumPy for


data analysis.

1. NumPy performs array-oriented computing.


2. It efficiently implements the multidimensional arrays.
3. It performs scientific computations.
4. It is capable of performing Fourier Transform and reshaping the data
stored in multidimensional arrays.
5. NumPy provides the in-built functions for linear algebra and random
number generation.

Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:

import numpy
Example:
import numpy
myarray = numpy.array([1, 2, 3, 4, 5])
print(myarray)
Output:
[1 2 3 4 5]

NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same
thing.
Create an alias with the as keyword while importing:

import numpy as np
Example:
import numpy as np
arr = np.array(['apple','banana','mango'])
print(arr)

Output:
['apple' 'banana' 'mango']

1-D Arrays
An array that has 0-D arrays 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)
Traversing 1-D array:
import numpy as np
a=np.array([23,45,67,78])
for i in a:
print(i)
output:
23
45
67
78

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.
NumPy has a whole sub module dedicated towards matrix operations
called numpy.mat
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]
[4 5 6]]

Traversing 2-D array:


import numpy as np
a= np.array([[1, 2, 3], [4, 5, 6]])
for i in a:
for j in i:
print(j)
output:
1
2
3
4
5
6

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:

Example:

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]]]

Traversing 2-D array:


import numpy as np
a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 15, 16]]])

for i in a:
for j in i:
for z in j:
print(z)
output:
1
2
3
4
5
6
7
8
9
10
15
16

Operations on Arrays[Array functions]


NumPy Array Indexing
Access Array Elements
Array indexing is the same as accessing an array element.

You can access an array element by referring to its index number.

The indexes in NumPy arrays start with 0, meaning that the first element has
index 0, and the second has index 1 etc.

Example:
Get the first element from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
print(arr[2])
Output:
1
2
Slicing arrays

Slicing in python means taking elements from one given index to another
given index.

We pass slice instead of index like this [start:end].

Example:

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

Joining NumPy Arrays

Joining means putting contents of two or more arrays in a single array.

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

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.
Example
Find the indexes where the value is 3:
import numpy as np
arr = np.array([1, 2, 3, 4, 3, 5])
x = np.where(arr == 3)
print(x)
Output:
(array([2,4]),)

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.
Example:
Sort the array:
import numpy as np
a= np.array([3, 2,1,4,7,5)
print(np.sort(a))

Output:
[1 2 3 4 5 7]

The Length of an Array

Use the len() method to return the length of an array (the number of
elements in an array).

Example:
import numpy as np
fruits=np.array(["apple", "banana", "mango"])

x = len(fruits)

print(x)
output:
3
Pandas In Python
What is 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.

Why Use Pandas?

Pandas allows us to analyze big data and make conclusions based on


statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.

Installation of Pandas
if you have Python and PIP already installed on a system, then installation of
Pandas is very easy.

Install it using this command:

C:\Users\your name>pip install pandas l pandas


Example:
C:\Users\lavanya>pip install pandas

Import Pandas
Once Pandas is installed, import it in your applications by adding
the import keyword:

import pandas

Example:
import pandas

mydataset = {
'names': ["Lavanya", "Bindu", "Indu"],
'age': [31,28,26]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)

Output:
Names age
0 Lavanya 31
1 Bindu 28
2 Indu 25

Pandas as pd
Pandas is usually imported under the pd alias.
alias: In Python alias are an alternate name for referring to the same
thing.
Create an alias with the as keyword while importing:
import pandas as pd

Pandas Series
What is a Series?
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type of value.
Example
Create a simple Pandas Series from a list:
import pandas as pd

a = [1, 3, 4]
myseries = pd.Series(a)
print(myseries)

output:
0 1
1 3
2 4
Dtype:int64

Create Labels
With the index argument, you can name your own labels.
Example
#Create your own labels:

import pandas as pd
ar = [1, 3, 4]
myseries= pd.Series(ar, index = ["a", "b", "c"])
print(myseries)
output:
a 1
b 3
c 4
Dtype:int64

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:
import pandas as pd
student = {"name":'Lavanya', "class": 'BCA', "age": 31}
data = pd.Series(student)
print(data)

output:
name Lavanya
class BCA
age 31
dtype:object

DataFrames
Data sets in Pandas are usually multi-dimensional tables, called
DataFrames.
Series is like a column, a DataFrame is the whole table.
Example
Create a DataFrame from two Series:
import pandas as pd
data = {
"Names": [‘Lavanya’,’Bindu’,’Indu’],
"age": [31, 28, 25], "Qualification": [‘MCA’,’BE’,’MSc’],
}

myframe = pd.DataFrame(data)

print(myframe)
Output:
Names age Qualification
0 Lavanya 31 MCA
1 Bindu 28 BE
2 Indu 25 MSc

Pandas Read CSV


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.
In our examples we will be using a CSV file called 'data.csv'.
Download data.csv. or Open data.csv

Example:
#Load the CSV into a DataFrame:

import pandas as pd

Dataframe1=pd.read_csv("Book2.CSV")

print(Dataframe1)

Output:
Name regno class address
0 lavanya 1001 BCA Bangaloe
1 bindu 1002 BSC mulbagal
2 indu 1003 Bcom kolar
3 chandu 1004 BA mulbagal
4 vani 1005 BSc mysore
5 divya 1006 BA hydrabad

Reading an excel file using Python



••
One can retrieve information from a spreadsheet(MS_EXCEL).
Reading, writing, or modifying the data can be done in Python can
be done in using different methods. Also, the user might have to go
through various sheets and retrieve data based on some criteria or
modify some rows and columns and do a lot of work. Here, we will
see the different methods to read our excel file.

Required Module
pip install xlrd

# import pandas lib as pd


import pandas as pd

# read by default 1st sheet of an excel file


dataframe1 = pd.read_excel('Book2.xlsx')

print(dataframe1)
Output:
0 regno name class age
1 1001 Bindu BE 28
2 1002 Indu MSC 25
3 1003 Divya BE 22
4 1004 Vani BSC 35
5 1005 Chandu MA 32
Data visualisation
Data visualization provides a good, organized pictorial
representation of the data which makes it easier to understand,
observe, analyze. In this, we will discuss how to visualize data
using Python.
Python provides various libraries that come with different features
for visualizing data. All these libraries come with different features
and can support various types of graphs. In this tutorial, we will be
discussing four such libraries.
• Matplotlib
• Seaborn
• Plotly
Matplotlib
Matplotlib is an easy-to-use, low-level data visualization library that
is built on NumPy arrays. It consists of various plots like scatter plot,
line plot, pie chart, bar chart, histogram, etc. Matplotlib provides a
lot of flexibility.

Installation of Matplotlib
If you have Python and PIP already installed on a system, then
installation of Matplotlib is very easy.

Install it using this command:

pip install matplotlib

Import Matplotlib

Once Matplotlib is installed, import it in your applications by adding


the import module statement:

import 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
plot() method:

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.

Example:
#Draw a line in a diagram from position (0,0) to position (6,250):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()
output:
Matplotlib Line chart
Linestyle

You can use the keyword argument linestyle, or shorter ls, to change the
style of the plotted line:

Example:

Use a dotted line:

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linestyle = 'dotted')


plt.show()
Output:

Matplotlib Bars
With Pyplot, you can use the bar() function to draw bar graphs:

import matplotlib.pyplot as plt


import numpy as np
x = np.array(["c", "c++", "java", "python"])
y = np.array([3, 6, 8, 10])
plt.bar(x,y)
plt.show()

Output:
Horizantal bar

With Pyplot, you can use the barh() function to draw horizontal bar
graphs:

import matplotlib.pyplot as plt


import numpy as np
x = np.array(["c", "c++", "java", "python"])
y = np.array([3, 6, 8, 10])
plt.barh(x,y)
plt.show()
Output:
Bar Color
The bar() and barh() take the keyword argument color to set the color of
the bars:

import matplotlib.pyplot as plt


import numpy as np
x = np.array(["c", "c++", "java", "python"])
y = np.array([3, 6, 8, 10])
plt.barh(x,y,color=”yellow”)
plt.show()

output:
Bar Width
The bar() takes the keyword argument width to set the width of the bars:

Example:

import numpy as np
x = np.array(["c", "c++", "java", "python"])
y = np.array([3, 6, 8, 10])
plt.barh(x,y,color=”hotpink”,width=0.3)
plt.show()
Output:

Matplotlib Pie Charts


With Pyplot, you can use the pie() function to draw pie charts:
Example
#A simple pie chart:
import matplotlib.pyplot as plt
import numpy as np

y = np.array([25, 15, 25, 35])

plt.pie(y)
plt.show()
output:

Labels
Add labels to the pie chart with the label parameter.

The label parameter must be an array with one label for each wedge:

Example
#A simple pie chart:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([30, 25, 25, 15])
mylabels = ["Python", "Java", "C++", "Cprogram"]

plt.pie(y, labels = mylabels)


plt.show()
Output:

Colors
You can set the color of each wedge with the colors parameter.

The colors parameter, if specified, must be an array with one value for
each wedge:

Example:

import matplotlib.pyplot as plt

import numpy as np

y = np.array([30, 25, 25, 15])


mylabels = ["Python", "Java", "C++", "Cprogram"]

mycolours=["hotpink","yellow","red","green"]

plt.pie(y, labels = mylabels,colors=mycolours)

plt.show()

Output:

You might also like