II BCA
Python Notes
Unit-5
GU Interface
A graphical user interface (GUI) is a desktop interface that allows
you to communicate with computers. They carry out various
activities on desktop computers, laptops, and other mobile devices.
Text-Editors and other graphical user interface applications build,
read, download, and erase various types of files. You can also play
games such as Sudoku, Chess, and Solitaire through these apps.
Google Chrome, Firefox, and Microsoft Edge are examples of
graphical user interface (GUI) Internet browsers.
Python has a variety of libraries, but these four stand out, especially
in terms of GUI.
Tkinter
Kivy
Python QT
wxPython
Tkinter is the first option for a lot of learners and developers
because it is quick and convenient to use. Tkinter is a Python library
that can be used to construct basic graphical user interface (GUI)
applications. In Python, it is the most widely used module for GUI
applications.
Next up, let’s get started with Tkinter.
Python Tkinter is the fastest and easiest way to create GUI
applications. Creating a GUI using Tkinter is an easy task.
Table of Content
Deepak T R, Lecturer, GFGC, Tiptur 1
II BCA
Python Notes
Create First Tkinter GUI Application
Tkinter Widget
Color and Font Option in Tkinter
Geometry Management
To create a Tkinter Python app, you follow these basic steps:
1. Import the tkinter module: This is done just like importing any
other module in Python. Note that in Python 2.x, the module is
named ‘Tkinter’, while in Python 3.x, it is na med ‘tkinter’.
2. Create the main window (container): The main window serves
as the container for all the GUI elements you’ll add later.
3. Add widgets to the main window: You can add any number of
widgets like buttons, labels, entry fields, etc., to the main window
to design the interface as desired.
4. Apply event triggers to the widgets: You can attach event
triggers to the widgets to define how they respond to user
interactions.
Create First Tkinter GUI Application
There are two main methods used which the user needs to remember
while creating the Python application with GUI.
Tk(): To create a main window, tkinter offers a method
‘Tk(screenName=None, baseName=None, className=’Tk’,
Deepak T R, Lecturer, GFGC, Tiptur 2
II BCA
Python Notes
useTk=1)’. To change the name of the window, you can change the
className to the desired one. The basic code used to create the
main window of the application is:
mainloop(): There is a method known by the name mainloop() is
used when your application is ready to run. mainloop() is an infinite
loop used to run the application, wait for an event to occur, and
process the event as long as the window is not closed.
Example: Output:
import tkinter
m = [Link]()
'''
widgets are added here
'''
[Link]()
Tkinter Widget
There are a number of widgets which you can put in your tkinter
application. Some of the major widgets are explained below:
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.
Example: Output:
from tkinter import *
root = Tk()
Deepak T R, Lecturer, GFGC, Tiptur 3
II BCA
Python Notes
w = Label(root,
text='GFGC,Tiptur')
[Link]()
[Link]()
2. Button
To add a button in your application, this widget is used. The general
syntax is:
w=Button(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
Buttons. Number of options can be passed as parameters separated
by commas.
Example: Output:
import tkinter as tk
r = [Link]()
[Link]('Counting Seconds')
button = [Link](r,
text='Stop', width=25,
command=[Link])
[Link]()
[Link]()
3. 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. There
are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated
by commas. Some of them are listed below.
Deepak T R, Lecturer, GFGC, Tiptur 4
II BCA
Python Notes
Example: Output:
from tkinter import *
master = Tk()
Label(master, text='First
Name').grid(row=0)
Label(master, text='Last
Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
[Link](row=0, column=1)
[Link](row=1, column=1)
mainloop()
4. 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)
There are number of options which are used to change the format of
this widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
Example: Output:
from tkinter import *
master = Tk()
var1 = IntVar()
Checkbutton(master,
text='male',
variable=var1).grid(row=0,
sticky=W)
var2 = IntVar()
Checkbutton(master,
Deepak T R, Lecturer, GFGC, Tiptur 5
II BCA
Python Notes
text='female',
variable=var2).grid(row=1,
sticky=W)
mainloop()
5. RadioButton
It is used to offer only one 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)
There are number of options which are used to change the format of
this widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
Example: Output:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root,
text='GfG', variable=v,
value=1).pack(anchor=W)
Radiobutton(root,
text='MIT', variable=v,
value=2).pack(anchor=W)
mainloop()
6. 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.
There are number of options which are used to change the format of
Deepak T R, Lecturer, GFGC, Tiptur 6
II BCA
Python Notes
the widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
Example: Output:
from tkinter import *
top = Tk()
Lb = Listbox(top)
[Link](1, 'Python')
[Link](2, 'Java')
[Link](3, 'C++')
[Link](4, 'Any other')
[Link]()
[Link]()
7. Scrollbar
It refers to the slide controller which will be used to implement
listed widgets. The general syntax is:
w = Scrollbar(master, option=value)
Example: Output:
from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
[Link](side=RIGHT, fill=Y)
mylist = Listbox(root,
yscrollcommand=[Link])
for line in range(100):
[Link](END, 'This is
line number' + str(line))
[Link](side=LEFT, fill=BOTH)
[Link](command=[Link]
iew)
Deepak T R, Lecturer, GFGC, Tiptur 7
II BCA
Python Notes
mainloop()
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of
the widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
8. Menu
It is used to create all kinds of menus used by the application. The
general syntax is:
w = Menu(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
this widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
Example: Output:
from tkinter import *
root = Tk()
menu = Menu(root)
[Link](menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File',
menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open.
..')
filemenu.add_separator()
filemenu.add_command(label='Exit'
, command=[Link])
helpmenu = Menu(menu)
menu.add_cascade(label='Help',
menu=helpmenu)
helpmenu.add_command(label='About
')
Deepak T R, Lecturer, GFGC, Tiptur 8
II BCA
Python Notes
mainloop()
[Link]
It refers to the multi-line and non-editable text. It works same as that
of Label. The general syntax is:
w = Message(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 widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
Example: Output:
from tkinter import *
main = Tk()
ourMessage = 'This is our
Message'
messageVar = Message(main,
text=ourMessage)
[Link](bg='lightgree
n')
[Link]()
[Link]()
9. Combobox
Combobox widget is created using the [Link] class from the
[Link] module. The values for the Combobox are specified using
the values parameter. The default value is set using the set method.
An event handler function on_select is bound to the Combobox
using the bind method, which updates a label with the selected item
whenever an item is selected.
Example: Output:
import tkinter as tk
from tkinter import ttk
def on_select(event):
Deepak T R, Lecturer, GFGC, Tiptur 9
II BCA
Python Notes
selected_item = combo_box.get()
[Link](text="Selected
Item: "+selected_item)
root = [Link]()
[Link]("Combobox Example")
# Create a label
label = [Link](root,
text="Selected Item: ")
[Link](pady=10)
# Create a Combobox widget
combo_box = [Link](root,
values=["Option 1", "Option 2",
"Option 3"])
combo_box.pack(pady=5)
# Set default value
combo_box.set("Option 1")
# Bind event to selection
combo_box.bind("<<ComboboxSelected>>"
, on_select)
[Link]()
Geometry Management
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.
1. pack() method
It organizes the widgets in blocks before placing in the parent
widget.
Example: Output:
import tkinter as tk
root = [Link]()
[Link]("Pack Example")
# Create three buttons
Deepak T R, Lecturer, GFGC, Tiptur 10
II BCA
Python Notes
button1 = [Link](root,
text="Button 1")
button2 = [Link](root,
text="Button 2")
button3 = [Link](root,
text="Button 3")
# Pack the buttons vertically
[Link]()
[Link]()
[Link]()
[Link]()
2. grid() method
It organizes the widgets in grid (table-like structure) before placing
in the parent widget.
Example: Output:
import tkinter as tk
root = [Link]()
[Link]("Grid Example")
# Create three labels
label1 = [Link](root,
text="Label 1")
label2 = [Link](root,
text="Label 2")
label3 = [Link](root,
text="Label 3")
# Grid the labels in a 2x2
grid
[Link](row=0, column=0)
[Link](row=0, column=1)
[Link](row=1, column=0,
columnspan=2)
Deepak T R, Lecturer, GFGC, Tiptur 11
II BCA
Python Notes
[Link]()
3. place() method
It organizes the widgets by placing them on specific positions
directed by the programmer.
Example: Output:
import tkinter as tk
root = [Link]()
[Link]("Place Example")
# Create a label
label = [Link](root,
text="Label")
# Place the label at specific
coordinates
[Link](x=50, y=50)
[Link]()
What is Tkinter in Python used for?
Tkinter is a built-in library in Python for creating graphical user
interfaces (GUIs). You can use it to design desktop applications
with familiar elements like buttons, windows, menus, and more. It
allows you to build interactive programs that users can navigate
visually.
What does TK() mean in Python?
In Python, Tk() is a function call from the tkinter module, which is
the standard interface to the Tk GUI toolkit. Calling Tk() initializes
a new Tkinter application, creating the main window where all the
GUI components (widgets) will be placed.
Is Tkinter the only GUI for Python?
No, Tkinter is not the only GUI library for Python. There are other
options like PyQt, Kivy, wxPython, and GTK+.
Deepak T R, Lecturer, GFGC, Tiptur 12
II BCA
Python Notes
What is a Tkinter window in Python?
A Tkinter window is the main graphical element, representing a
single on-screen window that can contain other UI elements.
Python SQlite
SQLite is a database management system used to store and manage
data in a structured format. It is often used in applications that need
to save data locally on a device or computer, such as mobile apps,
desktop software, and embedded systems. SQLite allows developers
to create databases, organize data into tables, and perform
operations like inserting, updating, and querying data.
What is the use of SQlite?
You should use SQLite because it is easy to use and does not
require a separate server to run. It is perfect for applications that
need to store data locally on a device, like mobile apps or desktop
software. SQLite is also fast and reliable, making it a good choice
for projects where simplicity and efficiency are important. Plus,
since it is self-contained, you can easily distribute SQLite databases
with your application without worrying about additional setup for
users.
Why SQLite?
SQLite does not require a separate server process or system to
Deepak T R, Lecturer, GFGC, Tiptur 13
II BCA
Python Notes
operate (serverless).
SQLite comes with zero-configuration, which means no setup or
administration needed.
A complete SQLite database is stored in a single cross-platform
disk file.
SQLite is very small and light weight, less than 400KiB fully
configured or less than 250KiB with optional features omitted.
SQLite is self-contained, which means no external dependencies.
SQLite transactions are fully ACID-compliant, allowing safe
access from multiple processes or threads.
SQLite supports most of the query language features found in
SQL92 (SQL2) standard.
SQLite is written in ANSI-C and provides simple and easy-to-use
API.
SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS)
and Windows (Win32, WinCE, WinRT).
SQLite3 can be integrated with Python using sqlite3 module, which
was written by Gerhard Haring. It provides an SQL interface
compliant with the DB-API 2.0 specification described by PEP 249.
You do not need to install this module separately because it is
shipped by default along with Python version 2.5.x onwards.
To use sqlite3 module, you must first create a connection object that
represents the database and then optionally you can create a cursor
object, which will help you in executing all the SQL statements.
Python sqlite3 module APIs
Following are important sqlite3 module routines, which can suffice
Deepak T R, Lecturer, GFGC, Tiptur 14
II BCA
Python Notes
your requirement to work with SQLite database from your Python
program. If you are looking for a more sophisticated application,
then you can look into Python sqlite3 module's official
documentation.
[Link]. API & Description
[Link](database [,timeout ,other optional
arguments])
This API opens a connection to the SQLite database
1 file. You can use ":memory:" to open a database
connection to a database that resides in RAM
instead of on disk. If database is opened
successfully, it returns a connection object.
[Link]([cursorClass])
This routine creates a cursor which will be used
throughout of your database programming with
2
Python. This method accepts a single optional
parameter cursorClass. If supplied, this must be a
custom cursor class that extends [Link].
3 [Link](sql [, optional parameters])
This routine executes an SQL statement. The SQL
statement may be parameterized (i. e. placeholders
instead of SQL literals). The sqlite3 module
Deepak T R, Lecturer, GFGC, Tiptur 15
II BCA
Python Notes
supports two kinds of placeholders: question marks
and named placeholders (named style).
For example − [Link]("insert into people
values (?, ?)", (who, age))
[Link](sql [, optional parameters])
This routine is a shortcut of the above execute
method provided by the cursor object and it creates
4
an intermediate cursor object by calling the cursor
method, then calls the cursor's execute method with
the parameters given.
[Link](sql, seq_of_parameters)
This routine executes an SQL command against all
5
parameter sequences or mappings found in the
sequence sql.
[Link](sql[, parameters])
This routine is a shortcut that creates an intermediate
6 cursor object by calling the cursor method, then calls
the cursor.s executemany method with the
parameters given.
[Link](sql_script)
This routine executes multiple SQL statements at
once provided in the form of script. It issues a
7
COMMIT statement first, then executes the SQL
script it gets as a parameter. All the SQL statements
should be separated by a semi colon (;).
Deepak T R, Lecturer, GFGC, Tiptur 16
II BCA
Python Notes
[Link](sql_script)
This routine is a shortcut that creates an intermediate
8 cursor object by calling the cursor method, then calls
the cursor's execute script method with the
parameters given.
connection.total_changes()
This routine returns the total number of database
9
rows that have been modified, inserted, or deleted
since the database connection was opened.
[Link]()
This method commits the current transaction. If you
10 don't call this method, anything you did since the
last call to commit() is not visible from other
database connections.
[Link]()
11 This method rolls back any changes to the database
since the last call to commit().
[Link]()
This method closes the database connection. Note
12 that this does not automatically call commit(). If you
just close your database connection without calling
commit() first, your changes will be lost!
13 [Link]()
This method fetches the next row of a query result
set, returning a single sequence, or None when no
Deepak T R, Lecturer, GFGC, Tiptur 17
II BCA
Python Notes
more data is available.
[Link]([size = [Link]])
This routine fetches the next set of rows of a query
result, returning a list. An empty list is returned
14
when no more rows are available. The method tries
to fetch as many rows as indicated by the size
parameter.
[Link]()
This routine fetches all (remaining) rows of a query
15
result, returning a list. An empty list is returned
when no rows are available.
Connect To Database
Following Python code shows how to connect to an existing database.
If the database does not exist, then it will be created and finally a
database object will be returned.
import sqlite3
conn = [Link]('[Link]')
print "Opened database successfully";
Here, you can also supply database name as the special
name :memory: to create a database in RAM. Now, let's run the
above program to create our database [Link] in the current
directory. You can change your path as per your requirement. Keep
the above code in [Link] file and execute it as shown below. If the
Deepak T R, Lecturer, GFGC, Tiptur 18
II BCA
Python Notes
database is successfully created, then it will display the following
message.
Create a Table
Following Python program will be used to create a
table in the previously created database.
#!/usr/bin/python
import sqlite3
conn = [Link]('[Link]')
print "Opened database successfully";
[Link]('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
[Link]()
When the above program is executed, it will create the
COMPANY table in your [Link] and it will display the
following messages −
Opened database successfully
Table created successfully
INSERT Operation
Following Python program shows how to create records in
the COMPANY table created in the above example.
import sqlite3
conn = [Link]('[Link]')
print "Opened database successfully";
Deepak T R, Lecturer, GFGC, Tiptur 19
II BCA
Python Notes
[Link]("INSERT INTO COMPANY
(ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00
)");
[Link]("INSERT INTO COMPANY
(ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (2, 'Allen', 25, 'Texas',
15000.00 )");
[Link]("INSERT INTO COMPANY
(ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (3, 'Teddy', 23, 'Norway',
20000.00 )");
[Link]("INSERT INTO COMPANY
(ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00
)");
[Link]()
print "Records created successfully";
[Link]()
When the above program is executed, it will create the given
records in the COMPANY table and it will display the following
two lines −
Opened database successfully
Records created successfully
SELECT Operation
Following Python program shows how to fetch and display
records from the COMPANY table created in the above
example.
#!/usr/bin/python
import sqlite3
conn = [Link]('[Link]')
Deepak T R, Lecturer, GFGC, Tiptur 20
II BCA
Python Notes
print "Opened database successfully";
cursor = [Link]("SELECT id, name, address,
salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
[Link]()
When the above program is executed, it will produce the
following result.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Deepak T R, Lecturer, GFGC, Tiptur 21
II BCA
Python Notes
UPDATE Operation
Following Python code shows how to use UPDATE statement
to update any record and then fetch and display the updated
records from the COMPANY table.
#!/usr/bin/python
import sqlite3
conn = [Link]('[Link]')
print "Opened database successfully";
[Link]("UPDATE COMPANY set SALARY = 25000.00
where ID = 1")
[Link]()
print "Total number of rows updated :",
conn.total_changes
cursor = [Link]("SELECT id, name, address,
salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
[Link]()
When the above program is executed, it will produce the
following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0
ID = 2
Deepak T R, Lecturer, GFGC, Tiptur 22
II BCA
Python Notes
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
DELETE Operation
Following Python code shows how to use DELETE statement
to delete any record and then fetch and display the
remaining records from the COMPANY table.
#!/usr/bin/python
import sqlite3
conn = [Link]('[Link]')
print "Opened database successfully";
[Link]("DELETE from COMPANY where ID = 2;")
[Link]()
print "Total number of rows deleted :",
conn.total_changes
cursor = [Link]("SELECT id, name, address,
salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
Deepak T R, Lecturer, GFGC, Tiptur 23
II BCA
Python Notes
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
[Link]()
When the above program is executed, it will produce the
following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Python Numpy
NumPy stands for numeric python which is a python package for
the computation and processing of the multidimensional and single
Deepak T R, Lecturer, GFGC, Tiptur 24
II BCA
Python Notes
dimensional array elements.
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.
The need of NumPy
With the revolution of data science, data analysis libraries like
NumPy, SciPy, Pandas, etc. have seen a lot of growth. With a much
easier syntax than other programming languages, python is the first
choice language for the data scientist.
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.
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.
Deepak T R, Lecturer, GFGC, Tiptur 25
II BCA
Python Notes
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.
NumPy Environment Setup
NumPy doesn't come bundled with Python. We have to install it
using the python pip installer. Execute the following command.
$ pip install numpy
It is best practice to install NumPy with the full SciPy stack. The
binary distribution of the SciPy stack is specific to the operating
systems.
What is a NumPy Array?
NumPy array is a multi-dimensional data structure that is the core of
scientific computing in Python.
All values in an array are homogenous (of the same data type).
They offer automatic vectorization and broadcasting.
They provide efficient memory management, ufuncs(universal
functions), support various data types, and are flexible with
Indexing and slicing.
Dimensionalities of array:
Deepak T R, Lecturer, GFGC, Tiptur 26
II BCA
Python Notes
Name Example
0D (zero-dimensional) Scalar – A single element
1D (one-dimensional) Vector- A list of integers.
2D (two-dimensional) Matrix- A spreadsheet of data
3D (three-dimensional) Tensor- Storing a color image
Create Array Object
NumPy array’s objects allow us to work with arrays in Python. The
array object is called ndarray.
array() function of the NumPy library creates a ndarray.
Example: Output
import numpy as np [1,2,3,4,5,6]
arr =
[Link]([1,2,3,4,5,6])
Example: Creating arrays using Output
list and tuples
import numpy as np [1 2 3 4]
li = [1, 2, 3, 4]
numpyArr = [Link](li)
print(numpyArr)
Example: Creating numpy Output
array using tuples
import numpy as np [1 2 3 4]
tup = (1, 2, 3, 4)
numpyArr = [Link](tup)
print(numpyArr)
Deepak T R, Lecturer, GFGC, Tiptur 27
II BCA
Python Notes
Types of Array:
1. One Dimensional Array
2. Multi-Dimensional Array
One Dimensional Array:
A one-dimensional array is a type of linear array.
One Dimensional Array
Example: one dimensional array Output
# importing numpy module List in python : [1, 2,
import numpy as np 3, 4]
# creating list Numpy Array in python :
[1 2 3 4]
list = [1, 2, 3, 4]
# creating numpy array
sample_array = [Link](list)
print("List in python : ",
list)
print("Numpy Array in
python :",sample_array)
Check data type for list and array:
print(type(list_1))
print(type(sample_array))
<class 'list'>
<class '[Link]'>
Multi-Dimensional Array:
Data in multidimensional arrays are stored in tabular
form.
# importing numpy module Output
Deepak T R, Lecturer, GFGC, Tiptur 28
II BCA
Python Notes
# importing numpy module Numpy multi
import numpy as np dimensional array
# creating list
in python
list_1 = [1, 2, 3, 4]
[[ 1 2 3 4]
list_2 = [5, 6, 7, 8]
[ 5 6 7 8]
list_3 = [9, 10, 11, 12]
# creating numpy array
[ 9 10 11 12]]
sample_array =
[Link]([list_1,list_2,list_3])
print("Numpy multi dimensional
array in python\n",sample_array)
Note: use [ ] operators inside [Link]() for
multi-dimensional
Anatomy of numpy array :
1. Axis: The Axis of an array describes the order of
the indexing into the array.
Axis 0 = one dimensional
Axis 1 = Two dimensional
Axis 2 = Three dimensional
2. Shape: indicates the size of an array along each
dimension. It is from a list/tuples.
Example:
Python3
# importing numpy module
import numpy as np
# creating list
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]
# creating numpy array
sample_array = [Link]([list_1,
Deepak T R, Lecturer, GFGC, Tiptur 29
II BCA
Python Notes
list_2,
list_3])
print("Numpy array :")
print(sample_array)
# print shape of the array
print("Shape of the array :",sample_array.shape)
Output:
Numpy array :
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Shape of the array : (3, 4)
Example:
Python3
import numpy as np
sample_array = [Link]([[0, 4, 2],
[3, 4, 5],
[23, 4, 5],
[2, 34, 5],
[5, 6, 7]])
print("shape of the array :",
sample_array.shape)
Output:
shape of the array : (5, 3)
3. Rank: The rank of an array is simply the number
of axes (or dimensions) it has.
The one-dimensional array has rank 1.
Rank 1
Deepak T R, Lecturer, GFGC, Tiptur 30
II BCA
Python Notes
The two-dimensional array has rank 2.
Rank 2
4. Data type objects (dtype): Data type objects
(dtype) is an instance of [Link] class. It
describes how the bytes in the fixed-size block of
memory corresponding to an array item should be
interpreted.
Example:
Python3
# Import module
import numpy as np
# Creating the array
sample_array_1 = [Link]([[0, 4, 2]])
sample_array_2 = [Link]([0.2, 0.4, 2.4])
# display data type
print("Data type of the array 1 :",
sample_array_1.dtype)
print("Data type of array 2 :",
sample_array_2.dtype)
Output:
Data type of the array 1 : int32
Data type of array 2 : float64
Some different way of creating Numpy Array :
Deepak T R, Lecturer, GFGC, Tiptur 31
II BCA
Python Notes
1. [Link](): The Numpy array object in
Numpy is called ndarray. We can create ndarray
using [Link]() function.
Syntax: [Link](parameter)
Example:
Python3
# import module
import numpy as np
#creating a array
arr = [Link]([3,4,5,5])
print("Array :",arr)
Output:
Array : [3 4 5 5]
2. [Link](): This is an inbuilt NumPy
function that returns evenly spaced values within a
given interval.
Syntax: [Link]([start, ]stop,
[step, ]dtype=None)
Example:
Python3
import numpy as np
[Link](1, 20 , 2, dtype = np.float32)
Output:
array([ 1., 3., 5., 7., 9., 11., 13., 15., 17., 19.],
dtype=float32)
Deepak T R, Lecturer, GFGC, Tiptur 32
II BCA
Python Notes
3. [Link](): This function returns evenly
spaced numbers over a specified between two limits.
Syntax: [Link](start, stop, num=50,
endpoint=True, retstep=False, dtype=None, axis=0)
Example 1:
Python3
import numpy as np
[Link](3.5, 10, 3)
Output:
array([ 3.5 , 6.75, 10. ])
Example 2:
Python3
import numpy as np
[Link](3.5, 10, 3,
dtype = np.int32)
Output:
array([ 3, 6, 10])
4. [Link](): This function create a new array
of given shape and type, without initializing value.
Syntax: [Link](shape, dtype=float,
order=’C’)
Example:
Python3
import numpy as np
[Link]([4, 3],
dtype = np.int32,
order = 'f')
Output:
Deepak T R, Lecturer, GFGC, Tiptur 33
II BCA
Python Notes
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
5. [Link](): This function is used to get a new
array of given shape and type, filled with ones(1).
Syntax: [Link](shape, dtype=None, order=’C’)
Example:
Python3
import numpy as np
[Link]([4, 3],
dtype = np.int32,
order = 'f')
Output:
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
6 . [Link](): This function is used to get a
new array of given shape and type, filled with
zeros(0).
Syntax: [Link](shape, dtype=None)
Example:
Python3
import numpy as np
[Link]([4, 3],
dtype = np.int32,
order = 'f')
Output:
array([[0, 0, 0],
[0, 0, 0],
Deepak T R, Lecturer, GFGC, Tiptur 34
II BCA
Python Notes
[0, 0, 0],
[0, 0, 0]])
Operations on Numpy Array
Arithmetic Operations:
Python3
# Python code to perform arithmetic
# operations on NumPy array
import numpy as np
# Initializing the array
arr1 = [Link](4, dtype =
np.float_).reshape(2, 2)
print('First array:')
print(arr1)
print('\nSecond array:')
arr2 = [Link]([12, 12])
print(arr2)
print('\nAdding the two arrays:')
print([Link](arr1, arr2))
print('\nSubtracting the two arrays:')
print([Link](arr1, arr2))
Deepak T R, Lecturer, GFGC, Tiptur 35
II BCA
Python Notes
print('\nMultiplying the two arrays:')
print([Link](arr1, arr2))
print('\nDividing the two arrays:')
print([Link](arr1, arr2))
Output:
First array:
[[ 0. 1.]
[ 2. 3.]]
Second array:
[12 12]
Adding the two arrays:
[[ 12. 13.]
[ 14. 15.]]
Subtracting the two arrays:
[[-12. -11.]
[-10. -9.]]
Multiplying the two arrays:
[[ 0. 12.]
[ 24. 36.]]
Deepak T R, Lecturer, GFGC, Tiptur 36
II BCA
Python Notes
Dividing the two arrays:
[[ 0. 0.08333333]
[ 0.16666667 0.25 ]]
[Link]() This function returns the
reciprocal of argument, element-wise. For elements
with absolute values larger than 1, the result is
always 0 and for integer 0, overflow warning is
issued. Example:
Python3
# Python code to perform reciprocal operation
# on NumPy array
import numpy as np
arr = [Link]([25, 1.33, 1, 1, 100])
print('Our array is:')
print(arr)
print('\nAfter applying reciprocal
function:')
print([Link](arr))
arr2 = [Link]([25], dtype = int)
print('\nThe second array is:')
print(arr2)
print('\nAfter applying reciprocal
function:')
print([Link](arr2))
Output
Deepak T R, Lecturer, GFGC, Tiptur 37
II BCA
Python Notes
Our array is:
[ 25. 1.33 1. 1. 100. ]
After applying reciprocal function:
[ 0.04 0.7518797 1. 1.
0.01 ]
The second array is:
[25]
After applying reciprocal function:
[0]
[Link]() This function treats elements in the
first input array as the base and returns it raised to
the power of the corresponding element in the
second input array.
Python3
# Python code to perform power operation
# on NumPy array
import numpy as np
arr = [Link]([5, 10, 15])
Deepak T R, Lecturer, GFGC, Tiptur 38
II BCA
Python Notes
print('First array is:')
print(arr)
print('\nApplying power function:')
print([Link](arr, 2))
print('\nSecond array is:')
arr1 = [Link]([1, 2, 3])
print(arr1)
print('\nApplying power function again:')
print([Link](arr, arr1))
Output:
First array is:
[ 5 10 15]
Applying power function:
[ 25 100 225]
Second array is:
[1 2 3]
Applying power function again:
[ 5 100 3375]
[Link]() This function returns the remainder of
division of the corresponding elements in the input
Deepak T R, Lecturer, GFGC, Tiptur 39
II BCA
Python Notes
array. The function [Link]() also produces
the same result.
Python3
# Python code to perform mod function
# on NumPy array
import numpy as np
arr = [Link]([5, 15, 20])
arr1 = [Link]([2, 5, 9])
print('First array:')
print(arr)
print('\nSecond array:')
print(arr1)
print('\nApplying mod() function:')
print([Link](arr, arr1))
print('\nApplying remainder() function:')
print([Link](arr, arr1))
Output:
First array:
[ 5 15 20]
Second array:
[2 5 9]
Applying mod() function:
[1 0 2]
Deepak T R, Lecturer, GFGC, Tiptur 40
II BCA
Python Notes
Applying remainder() function:
[1 0 2]
Data Visualization using Matplotlib
In today’s world, a lot of data is being generated on a daily basis.
And sometimes to analyse this data for certain trends, patterns may
become difficult if the data is in its raw format. To overcome this
data visualization comes into play. Data visualization provides a
good, organized pictorial representation of the data which makes it
easier to understand, observe, analyse. In this tutorial, we will
discuss how to visualize data using Python.
Data visualization 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
Bokeh
Plotly
pandas
We will discuss these libraries one by one and will plot some most
Deepak T R, Lecturer, GFGC, Tiptur 41
II BCA
Python Notes
commonly used graphs.
Matplotlib
Matplotlib is a powerful plotting library in Python used for creating
static, animated, and interactive visualizations. Matplotlib’s primary
purpose is to provide users with the tools and functionality to
represent data graphically, making it easier to analyse and
understand. It was originally developed by John D. Hunter in 2003
and is now maintained by a large community of developers.
Key Features of Matplotlib:
Versatility: Matplotlib can generate a wide range of plots,
including line plots, scatter plots, bar plots, histograms, pie
charts, and more.
Customization: It offers extensive customization options to
control every aspect of the plot, such as line styles, colors,
markers, labels, and annotations.
Integration with NumPy: Matplotlib integrates seamlessly with
NumPy, making it easy to plot data arrays directly.
Publication Quality: Matplotlib produces high-quality plots
suitable for publication with fine-grained control over the plot
aesthetics.
Extensible: Matplotlib is highly extensible, with a large
ecosystem of add-on toolkits and extensions like Seaborn, Pandas
plotting functions, and Basemap for geographical plotting.
Cross-Platform: It is platform-independent and can run on
Deepak T R, Lecturer, GFGC, Tiptur 42
II BCA
Python Notes
various operating systems, including Windows, macOS, and
Linux.
Interactive Plots: Matplotlib supports interactive plotting
through the use of widgets and event handling, enabling users to
explore data dynamically.
What is a Matplotlib Figure?
In Matplotlib, a figure is the top-level container that holds all the
elements of a plot. It represents the entire window or page where
the plot is drawn.
Basic Components or Parts of Matplotlib Figure
The parts of a Matplotlib figure include (as shown in the figure
above):
1. Figures in Matplotlib: The Figure object is the top-level
container for all elements of the plot. It serves as the canvas on
Deepak T R, Lecturer, GFGC, Tiptur 43
II BCA
Python Notes
which the plot is drawn. You can think of it as the blank sheet
of paper on which you’ll create your visualization.
2. Axes in Matplotlib: Axes are the rectangular areas within the
figure where data is plotted. Each figure can contain one or
more axes, arranged in rows and columns if necessary. Axes
provide the coordinate system and are where most of the
plotting occurs.
3. Axis in Matplotlib: Axis objects represent the x-axis and y-
axis of the plot. They define the data limits, tick locations, tick
labels, and axis labels. Each axis has a scale and a locator that
determine how the tick marks are spaced.
4. Marker in Matplotlib: Markers are symbols used to denote
individual data points on a plot. They can be shapes such as
circles, squares, triangles, or custom symbols. Markers are often
used in scatter plots to visually distinguish between different
data points.
6. Adding lines to Figures: Lines connect data points on a plot
and are commonly used in line plots, scatter plots with
connected points, and other types of plots. They represent the
relationship or trend between data points and can be styled with
different colors, widths, and styles to convey additional
information.
7. Matplotlib Title: The title is a text element that provides a
descriptive title for the plot. It typically appears at the top of the
figure and provides context or information about the data being
visualized.
Deepak T R, Lecturer, GFGC, Tiptur 44
II BCA
Python Notes
8. Axis Labels in Matplotlib: Labels are text elements that
provide descriptions for the x-axis and y-axis. They help
identify the data being plotted and provide units or other
relevant information.
9. Ticks: Tick marks are small marks along the axis that indicate
specific data points or intervals. They help users interpret the
scale of the plot and locate specific data values.
10. Tick Labels: Tick labels are text elements that provide labels
for the tick marks. They usually display the data values
corresponding to each tick mark and can be customized to show
specific formatting or units.
11. Matplotlib Legend: Legends provide a key to the symbols or
colors used in the plot to represent different data series or
categories. They help users interpret the plot and understand the
meaning of each element.
12. Matplotlib Grid Lines: Grid lines are horizontal and vertical
lines that extend across the plot, corresponding to specific data
intervals or divisions. They provide a visual guide to the data
and help users identify patterns or trends.
13. Spines of Matplotlib Figures: Spines are the lines that form
the borders of the plot area. They separate the plot from the
surrounding whitespace and can be customized to change the
appearance of the plot borders.
Different Types of Plots in Matplotlib
Matplotlib offers a wide range of plot types to suit various data
visualization needs. Here are some of the most commonly used
Deepak T R, Lecturer, GFGC, Tiptur 45
II BCA
Python Notes
types of plots in Matplotlib:
Line Graph
Stem Plot
Bar chart
Histograms
Scatter Plot
Stack Plot
Box Plot
Pie Chart
Creating Different Types of Plot
In data visualization, creating various types of plots is essential for
effectively conveying insights from data. Below, we’ll explore how
to create different types of plots using Matplotlib, a powerful
plotting library in Python.
Line Graph in Matplotlib
Line graphs are commonly used to visualize trends over time or
relationships between variables. We’ll learn how to create visually
appealing line graphs to represent such data.
Example
Python3
import [Link] as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
# This will plot a simple line chart
# with elements of x as x axis and y
# as y axis
[Link](x, y)
[Link]("Line Chart")
Deepak T R, Lecturer, GFGC, Tiptur 46
II BCA
Python Notes
# Adding the legends
[Link](["Line"])
[Link]()
Output
Stem Plot in Matplotlib
A stem plot, also known as a stem-and-leaf plot, is a type of plot
used to display data along a number line. Stem plots are
particularly useful for visualizing discrete data sets, where the
values are represented as “stems” extending from a baseline, with
data points indicated as “leaves” along the stems. let’s understand
the components of a typical stem plot:
Stems: The stems represent the main values of the data and are
typically drawn vertically along the y-axis.
Leaves: The leaves correspond to the individual data points and
are plotted horizontally along the stems.
Baseline: The baseline serves as the reference line along which
the stems are drawn.
Example
Python3
# importing libraries
import [Link] as plt
import numpy as np
Deepak T R, Lecturer, GFGC, Tiptur 47
II BCA
Python Notes
x = [Link](0.1, 2 * [Link], 41)
y = [Link]([Link](x))
[Link](x, y, use_line_collection = True)
[Link]()
Output
Bar chart in Matplotlib
A bar plot or bar chart is a graph that represents the category of
data with rectangular bars with lengths and heights that is
proportional to the values which they represent. The bar plots can
be plotted horizontally or vertically. A bar chart describes the
comparisons between the discrete categories. It can be created
using the bar() method.
Example
Python3
import [Link] as plt
# data to display on plots
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]
# This will plot a simple bar chart
[Link](x, y)
# Title to the plot
[Link]("Bar Chart")
[Link](["bar"])
[Link]()
Deepak T R, Lecturer, GFGC, Tiptur 48
II BCA
Python Notes
Output
Plotting Histogram in Matplotlib
A histogram is basically used to represent data in the form of some
groups. It is a type of bar plot where the X-axis represents the bin
ranges while the Y-axis gives information about frequency. To
create a histogram the first step is to create a bin of the ranges, then
distribute the whole range of the values into a series of intervals,
and count the values which fall into each of the intervals. Bins are
clearly identified as consecutive, non-overlapping intervals of
variables.
Example
Python3
import [Link] as plt
# data to display on plots
x = [1, 2, 3, 4, 5, 6, 7, 4]
# This will plot a simple histogram
[Link](x, bins = [1, 2, 3, 4, 5, 6, 7])
# Title to the plot
[Link]("Histogram")
# Adding the legends
[Link](["bar"])
[Link]()
Output
Deepak T R, Lecturer, GFGC, Tiptur 49
II BCA
Python Notes
Scatter Plot in Matplotlib
Scatter plots are ideal for visualizing the relationship between two
continuous variables. We’ll see how scatter plots help identify
patterns, correlations, or clusters within data points.
Python3
import [Link] as plt
# data to display on plots
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]
# This will plot a simple scatter chart
[Link](x, y)
# Adding legend to the plot
[Link]("A")
# Title to the plot
[Link]("Scatter chart")
[Link]()
Output
Stack Plot in Matplotlib
Deepak T R, Lecturer, GFGC, Tiptur 50
II BCA
Python Notes
Stackplot, also known as a stacked area plot, is a type of plot that
displays the contribution of different categories or components to
the total value over a continuous range, typically time. It is
particularly useful for illustrating changes in the distribution of
data across multiple categories or groups.
Python3
import [Link] as plt
# List of Days
days = [1, 2, 3, 4, 5]
# No of Study Hours
Studying = [7, 8, 6, 11, 7]
# No of Playing Hours
playing = [8, 5, 7, 8, 13]
# Stackplot with X, Y, colors value
[Link](days, Studying, playing, colors =['r',
'c'])
# Days
[Link]('Days')
# No of hours
[Link]('No of Hours')
# Title of Graph
[Link]('Representation of Study and \
Playing wrt to Days')
# Displaying Graph
[Link]()
Output
Deepak T R, Lecturer, GFGC, Tiptur 51
II BCA
Python Notes
Pie Chart in Matplotlib
A Pie Chart is a circular statistical plot that can display only one
series of data. The area of the chart is the total percentage of the
given data. The area of slices of the pie represents the percentage
of the parts of the data. The slices of pie are called wedges. The
area of the wedge is determined by the length of the arc of the
wedge.
Python3
import [Link] as plt
# data to display on plots
x = [1, 2, 3, 4]
# this will explode the 1st wedge
# i.e. will separate the 1st wedge
# from the chart
e =(0.1, 0, 0, 0)
# This will plot a simple pie chart
[Link](x, explode = e)
# Title to the plot
[Link]("Pie chart")
[Link]()
Output
Deepak T R, Lecturer, GFGC, Tiptur 52
II BCA
Python Notes
Pandas:
Pandas is an open-source Python library used for data manipulation, analysis and
cleaning. It provides fast and flexible tools to work with tabular data, similar to
spreadsheets or SQL tables.
Why Pandas?
The beauty of Pandas is that it simplifies the task related to data frames and makes it
simple to do many of the time-consuming, repetitive tasks involved in working with
data frames, such as:
Import datasets - available in the form of spreadsheets, comma-separated values
(CSV) files, and more.
Data cleansing - dealing with missing values and representing them as NaN,
NA, or NaT.
Size mutability - columns can be added and removed from DataFrame and
higher-dimensional objects.
Data normalization – normalize the data into a suitable format for analysis.
Data alignment - objects can be explicitly aligned to a set of labels.
Intuitive merging and joining data sets – we can merge and join datasets.
Reshaping and pivoting of datasets – datasets can be reshaped and pivoted as
per the need.
Efficient manipulation and extraction - manipulation and extraction of specific
parts of extensive datasets using intelligent label-based slicing, indexing, and
subsetting techniques.
Statistical analysis - to perform statistical operations on datasets.
Data visualization - Visualize datasets and uncover insights.
Deepak T R, Lecturer, GFGC, Tiptur 53
II BCA
Python Notes
Applications of Pandas
The most common applications of Pandas are as follows:
Data Cleaning: Pandas provides functionalities to clean messy data, deal with
incomplete or inconsistent data, handle missing values, remove duplicates, and
standardize formats to do effective data analysis.
Data Exploration: Pandas easily summarize statistics, find trends, and visualize
data using built-in plotting functions, Matplotlib, or Seaborn integration.
Data Preparation: Pandas may pivot, melt, convert variables, and merge
datasets based on common columns to prepare data for analysis.
Data Analysis: Pandas supports descriptive statistics, time series analysis, group-
by operations, and custom functions.
Data Visualisation: Pandas itself has basic plotting capabilities; it integrates and
supports data visualization libraries like Matplotlib, Seaborn, and Plotly to create
innovative visualizations.
Time Series Analysis: Pandas supports date/time indexing, resampling,
frequency conversion, and rolling statistics for time series data.
Data Aggregation and Grouping: Pandas groupby() function lets you aggregate
data and compute group-wise summary statistics or apply functions to groups.
Data Input/Output: Pandas makes data input and export easy by reading and
writing CSV, Excel, JSON, SQL databases, and more.
Machine Learning: Pandas works well with Scikit-learn for data preparation,
feature engineering, and model input data.
Web Scraping: Pandas may be used with BeautifulSoup or Scrapy to parse and
analyse structured web data for web scraping and data extraction.
Financial Analysis: Pandas is commonly used in finance for stock market data
analysis, financial indicator calculation, and portfolio optimization.
Deepak T R, Lecturer, GFGC, Tiptur 54
II BCA
Python Notes
Text Data Analysis: Pandas' string manipulation, regular expressions, and text
mining functions help analyse textual data.
Experimental Data Analysis: Pandas makes manipulating and analysing large
datasets, performing statistical tests, and visualizing results easy.
Getting Started with Pandas
Let’s see how to start working with the Python Pandas library:
Installing Pandas
The first step in working with Pandas is to ensure whether it is installed in the system or
not. If not, then we need to install it on our system using the pip command.
Follow these steps to install Pandas:
Step 1: Type ‘cmd’ in the search box and open it.
Step 2: Locate the folder using the cd command where the python-pip file has been
installed.
Step 3: After locating it, type the command:
pip install pandas
Importing Pandas
After the Pandas have been installed in the system, you need to import the library. This
module is generally imported as follows:
import pandas as pd
Note: Here, pd is referred to as an alias for the Pandas. However, it is not necessary to
import the library using the alias, it just helps in writing less code every time a method
or property is called.
Data Structures in Pandas Library
Pandas generally provide two data structures for manipulating data. They are:
Series
DataFrame
Deepak T R, Lecturer, GFGC, Tiptur 55
II BCA
Python Notes
Pandas Series
A Pandas Series is a one-dimensional labelled array capable of holding data of any type
(integer, string, float, Python objects, etc.). The axis labels are collectively
called indexes.
The Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique
but must be of a hashable type.
The object supports both integer and label-based indexing and provides a host of
methods for performing operations involving the index.
Creating a Series
Pandas Series is created by loading the datasets from existing storage (which can be a
SQL database, a CSV file, or an Excel file).
Pandas Series can be created from lists, dictionaries, scalar values, etc.
Example: Creating a series using the Pandas Library.
Python
Output
import pandas as pd
Pandas Series: Series([], dtype:
import numpy as np
float64)
# Creating empty series
Pandas Series:
ser = [Link]()
0 g
print("Pandas Series: ", ser)
1 e
# simple array
2 e
data = [Link](['g', 'e', 'e', 'k', 's'])
3 k
ser = [Link](data)
4 s
print("Pandas Series:\n", ser)
dtype: object
Deepak T R, Lecturer, GFGC, Tiptur 56
II BCA
Python Notes
Pandas DataFrame
Pandas DataFrame is a two-dimensional data structure with labelled axes (rows and
columns).
Creating DataFrame
Pandas DataFrame is created by loading the datasets from existing storage (which can
be a SQL database, a CSV file, or an Excel file).
Pandas DataFrame can be created from lists, dictionaries, a list of dictionaries, etc.
Example: Creating a DataFrame Using the Pandas Library
Python
Empty DataFrame
import pandas as pd
Columns: []
# Calling DataFrame constructor
Index: []
df = [Link]()
0
print(df)
0 Geeks
# list of strings
1 For
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for',
2 Geeks
'Geeks']
3 is
# Calling DataFrame constructor on list
4 portal
df = [Link](lst)
5 for
print(df)
6 Geeks
Operations in Pandas
Pandas provides essential operations for working with structured data efficiently. The
sections below introduce the most commonly used functionalities with short
explanations and simple examples.
1. Loading Data: This operation reads data from files such as CSV, Excel or JSON into
Deepak T R, Lecturer, GFGC, Tiptur 57
II BCA
Python Notes
a DataFrame.
import pandas as pd
df = pd.read_csv("[Link]")
print([Link]())
Output:
Roll No Name address
0 101 deepak Tiptur
1 102 Mahesh JC Pura
2 103 Dharani Tiptur
3 104 Harish Madugiri
2. Viewing and Exploring Data: After loading data, it is important to understand its
structure and content. This methods allow you to inspect rows, summary statistics and
metadata.
print([Link]())
Output:
<class '[Link]'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Roll No 4 non-null int64
1 Name 4 non-null object
2 address 4 non-null object
dtypes: int64(1), object(2)
memory usage: 228.0+ bytes
None
3. Selecting and Filtering Data: This operation retrieves specific columns, rows or
Deepak T R, Lecturer, GFGC, Tiptur 58
II BCA
Python Notes
records that match a condition. It allows precise extraction of required information.
Reg = df[df['Register'] > 103]
print(Reg)
Register Name address
3 104 Harish Madugiri
5. Adding and Removing Columns: You can create new columns based on existing
ones or delete unwanted columns from the DataFrame.
import pandas as pd
df = pd.read_csv("[Link]")
df['Total'] = df['a'] + df['b']
print([Link]())
Register Name address a b Total
0 101 deepak Tiptur 10 15 25
1 102 Mahesh JC Pura 15 20 35
2 103 Dharani Tiptur 15 25 40
3 104 Harish Madugiri 10 20 30
Two marks Questions on Pandas
1. What is pandas used for?
Pandas is a Python library used for data manipulation and analysis. It is widely
used in the domain of data science, engineering, research, agriculture science,
management, statistics, and other related fields where you need to work with
datasets.
2. Define series in pandas.
A Series in Pandas is a one-dimensional labeled array capable of holding data of any
type (integer, string, float, Python objects, etc.).
3. What are the two main datatypes in python?
Deepak T R, Lecturer, GFGC, Tiptur 59
II BCA
Python Notes
The two primary data structures of pandas are −
Series (1-dimensional)
DataFrame (2-dimensional)
4. Why do we need pandas in python?
Pandas is the best tool for handling real-world messy data. It is built on top of
NumPy and is open-source. Pandas allows for fast and effective data manipulation
using its data structures, Series and DataFrame. It handles missing data, supports
multiple file formats, and facilitates data cleaning and analysis.
5. What is the difference between pandas and numpy?
Pandas provides high-level data manipulation tools built on top of NumPy. The
Pandas module mainly works with tabular data, whereas the NumPy module works
with numerical data.
Two marks Questions on Numpy
1. What is NumPy?
NumPy (Numerical Python) is a Python library used for numerical computing. It
provides support for working with large, multi-dimensional arrays and matrices, along
with a collection of mathematical functions to operate on them efficiently.
Any Two Features of NumPy
1. High-performance multi-dimensional array objects (ndarray) for fast computation.
2. Vectorized operations that make numerical calculations faster and more efficient
compared to Python lists.
2 . What is an ndarray in NumPy?
An ndarray (N-dimensional array) in NumPy is a powerful, homogeneous, multi-
dimensional array object that stores elements of the same data type. It allows fast
mathematical and logical operations on large datasets.
This is the core data structure of NumPy, used for efficient numerical computation.
Deepak T R, Lecturer, GFGC, Tiptur 60
II BCA
Python Notes
3. How do you create a NumPy array?
You can create a NumPy array using the [Link]() function by passing a list, tuple, or nested list.
Example
import numpy as np
arr = [Link]([1, 2, 3, 4])
This creates a 1-dimensional NumPy array containing the elements 1, 2, 3, and 4.
4. What does the function [Link]() do?
The function [Link]() in NumPy generates an array with evenly spaced values within a given
range.
It works similar to Python’s range() but returns a NumPy array.
Example
[Link](1, 10, 2)
This creates an array:
[1, 3, 5, 7, 9]
5. What is the use of dtype in NumPy arrays?
The dtype (data type) in NumPy specifies the type of elements stored in an array, such as int32,
float64, bool, etc.
It helps NumPy determine how much memory to use for each element and how operations should be
performed.
Example
arr = [Link]([1, 2, 3], dtype='float32')
6. Write the purpose of [Link]() and [Link]().
[Link]() is used to create a NumPy array filled with all zeros.
You must specify the shape of the array.
[Link]() is used to create a NumPy array filled with all ones.
You must specify the shape of the array.
Example
[Link]((2, 3)) # 2x3 array of zeros
[Link]((3, 2)) # 3x2 array of ones
Two marks Questions on Matplotlib
Deepak T R, Lecturer, GFGC, Tiptur 61
II BCA
Python Notes
1. What is matplotlib?
Matplotlib is a Python library used for data visualization. It allows you to create a wide range of
static, animated, and interactive plots such as line charts, bar charts, histograms, scatter plots, and
more.
It is widely used for scientific computing, data analysis, and graphical representation of data.
?
2. What is the use of Pyplot module in Matplotlib?
The pyplot module in Matplotlib provides a collection of functions that make it easy to create and
customize plots.
It works similar to MATLAB’s plotting interface and is commonly imported as:
import [Link] as plt
It allows you to draw plots, add titles, labels, legends, and display the graph easily.
3. Write the purpose of [Link]().
[Link]() is used to draw a line plot in Matplotlib.
It plots data points on a graph and connects them with a line, helping visualize trends or relationships
between variables.
Example
[Link](x, y)
4. What is the figure in Matplotlib?
A figure in Matplotlib is the overall window or canvas on which all plots, charts, and graphics
are drawn.
It can contain one or more subplots (axes) and serves as the main container for the entire
visualization.
It is created using:
[Link]()
5. What is histogram? Which function us used to draw it?
A histogram is a graphical representation that shows the distribution of numerical data.
It divides the data into bins (ranges) and displays how many values fall into each bin.
The function used to draw a histogram in Matplotlib is:
[Link]()
6. What is bar chart? Which function is used to draw it?
A bar chart is a graphical representation used to display categorical data using rectangular bars.
The height or length of each bar represents the value of the corresponding category.
Deepak T R, Lecturer, GFGC, Tiptur 62
II BCA
Python Notes
The function used to draw a bar chart in Matplotlib is:
[Link]()
********************Good Luck************************
Deepak T R, Lecturer, GFGC, Tiptur 63