Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Unit 5 PythonPackages (Numpy,Pandas,Tkinter)

The document provides an overview of essential Python packages including NumPy for numerical computing, Pandas for data manipulation, and Matplotlib for data visualization. It details their key features, applications, and the relationship between them, emphasizing their importance in data analysis and scientific research. Additionally, it covers data structures in Pandas, exception handling in Python, and the Tkinter library for creating graphical user interfaces.

Uploaded by

shantanu270805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit 5 PythonPackages (Numpy,Pandas,Tkinter)

The document provides an overview of essential Python packages including NumPy for numerical computing, Pandas for data manipulation, and Matplotlib for data visualization. It details their key features, applications, and the relationship between them, emphasizing their importance in data analysis and scientific research. Additionally, it covers data structures in Pandas, exception handling in Python, and the Tkinter library for creating graphical user interfaces.

Uploaded by

shantanu270805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

UNIT - 5

PYTHON PACKAGES
1. NumPy

NumPy (Numerical Python) is a foundational Python library for numerical and scientific computing, especially for handling large,
multidimensional datasets.

Creator: Travis Oliphant developed NumPy in 2005 to replace the Numeric library and address its limitations.

Key Features:

1. Array Manipulation:
● Efficiently handles n-dimensional arrays (ndarray) for numeric data.
● Faster and more memory-efficient than Python lists.
2. Mathematical Operations:
● Basic arithmetic: addition, subtraction, multiplication, division.
● Advanced functions: sine, cosine, exponential, logarithms.
3. Broadcasting:
● Perform operations on arrays of different shapes without manual resizing.
4. Linear Algebra:
● Compute matrix operations like determinants, inverses, and eigenvalues.
● Perform dot products and matrix multiplication.
5. Random Number Generation:
● Generate random datasets for testing and simulations.
● Supports uniform, normal, and other probability distributions.
Applications:

● Used in simulations, machine learning, image processing, and scientific research.


● Forms the base for libraries like Pandas, SciPy, and TensorFlow.

Why Use NumPy?

NumPy accelerates computations, enabling efficient processing of large datasets with minimal code.
2. Pandas

Pandas is a Python library designed for data manipulation and analysis, making it easier to work with structured data such as tables
and time-series data.

Creator: Wes McKinney created Pandas in 2008 for easier data manipulation in Python.

Key Features:

1. Core Data Structures:


● Series: One-dimensional labeled array (e.g., a column in a spreadsheet).
● DataFrame: Two-dimensional labeled structure (e.g., a table with rows and columns).
2. Data I/O:
● Read and write operations for CSV, Excel, SQL, JSON, and more.
● Seamless integration with databases and files.
3. Data Cleaning:
● Fill, drop, or interpolate missing values.
● Remove duplicates and format data for consistency.
4. Data Transformation:
● Adding, modifying, or deleting columns and rows.
● Perform operations like merging, concatenating, and reshaping data.
● Apply group operations for aggregation (e.g., sum, average).
5. Time-Series Analysis:
● Built-in support for handling date and time data.
● Resampling and rolling computations for trends.
Applications:

● Used in finance, marketing, and healthcare for data preparation and analysis.
● Suitable for exploratory data analysis (EDA).

Why Use Pandas?

Pandas simplifies complex data operations and allows users to work efficiently with real-world datasets.
3. Matplotlib

Matplotlib is a powerful library for data visualization, helping users create clear, informative charts and graphs to understand data patterns.

Creator: John D. Hunter developed Matplotlib in 2003 to mimic MATLAB's plotting capabilities in Python.

Key Features:

1. Basic Plot Types:


● Create line plots, bar charts, scatter plots, pie charts, and histograms.
2. Customization:
● Customize colors, markers, labels, gridlines, and axes.
● Annotate plots with text, arrows, and legends.
3. Advanced Visualization:
● Create subplots for comparing multiple datasets.
● Generate 3D plots for advanced data exploration.
4. Interactive Features:
● Zoom, pan, and save figures for deeper analysis.
● Works with Jupyter Notebooks for real-time adjustments.
5. Integration:
● Seamlessly integrates with Pandas and NumPy for direct plotting.
● Export plots in multiple formats (e.g., PNG, PDF, SVG).
Applications:

● Used in data science, reporting, and research to present findings visually.


● Ideal for creating static and dynamic graphs.

Why Use Matplotlib?

Matplotlib provides unparalleled control over visual elements, making it essential for data presentation and storytelling.
RELATIONSHIP BETWEEN NUMPY, PANDAS AND MATPLOTLIB
DATA STRUCTURE IN PANDAS
A data structure is a way to arrange the data in such a way that so it can be accessed
quickly and we can perform various operation on this data like- retrieval, deletion,
modification etc.
Pandas deals with 3 data structure
1. Series
2. Data Frame
3. Panel

Series-
Series is a one-dimensional array like structure with homogeneous data as well as
heterogeneous data, which can be used to handle and manipulate data. What makes it
special is its index attribute, which has incredible functionality and is mutable.
It has two parts
1. Data part (An array of actual data)
2. Associated index with data (associated array of indexes or data labels)
✓ We can say that Series is a labeled one-dimensional array which can hold any type of
data.
✓ Data of Series is always mutable, means it can be changed.
✓ But the size of Data of Series is always immutable, means it cannot be changed.
✓ Series may be considered as a Data Structure with two arrays out which one array works
as Index (Labels) and the second array works as original Data.
✓ Row Labels in Series are called Index.
Creating Series Using Range Function:
Output

Delete an element from Series


Label-based Indexing (used in loc)

Label-based indexing means accessing elements in a data structure using explicit labels(declare by
programmer) or names assigned to rows or columns. These labels can be strings, integers, or other types,
and they are used to uniquely identify data points.
Position-based Indexing (used in iloc)
Position-based indexing means accessing elements in a data structure using their numerical position. This
position is based on the order of elements, starting from 0 for the first element, regardless of any labels
assigned.

1. loc

● Label-based indexing: Accesses elements using explicit index labels.


● Can handle non-integer and integer labels.
● Supports slicing with inclusive bounds (stop included).

2. iloc

● Position-based indexing: Accesses elements using integer positions (like Python lists).
● Cannot use custom labels; works only with numerical positions.
● Supports slicing with exclusive upper bound (stop excluded).
A data frame can be created using any of the following
1. Series
2. Lists
3. Dictionary
4. A numpy 2D array
Creating a DataFrame from a Dictionary in Pandas
Creating a DataFrame from a NumPy 2D Array:
Read a CSV file into a Pandas DataFrame

CSV files are the Comma Separated Files. It allows users to load tabular data into a DataFrame, which
is a powerful structure for data manipulation and analysis. To access data from the CSV file, we
require a function read_csv() from Pandas that retrieves data in the form of the data frame.
Example 2: Display the first N rows of a Pandas DataFrame
Example 3: Filter rows in a Pandas DataFrame based on a condition
Example 4: Calculate Mean and sum for Pandas Dataframe
Note: To know more about pandas visit
https://www.geeksforgeeks.org/pandas-cheat-sheet/
Error & Exception Handling
● An exception is a type of error that occurs during the runtime of a program
● Exception handling is a mechanism in Python to deal with exceptions and prevent the program
from crashing. It allows you to write code that anticipates potential problems and provides
solutions or alternative actions.

● Python has many built-in exceptions (ArithmeticError, ZeroDivisionError, AssertionError,


IndexError, KeyError, SyntaxError, IndentationError, FileNotFoundError etc) that are raised when
your program encounters an error.

● When the exception occurs Python interpreter stops the current process and passes it to the
calling process until it is handled. If exception is not handled the program will crash.

● Exceptions in python can be handled using a try statement. The try block lets you test a block of
code for errors.

● The block of code which can raise an exception is placed inside the try clause. The code that will
handle the exceptions is written in the except clause.

● The finally code block will execute regardless of the result of the try and except blocks.The
primary purpose of the finally block is to ensure that essential cleanup operations (e.g., closing
files, releasing resources, etc.) are performed, avoiding resource leaks or inconsistent states.
● We can also use the else keyword to define a block of code to be executed if no exceptions were
raised.
● Python also allows us to create our own exceptions that can be raised from the program using the
raise keyword and caught using the except clause. We can define what kind of error to
raise, and the text to print to the user.

Note:try-except works only for runtime errors because it operates during the
program's execution phase.
Without Exception Handling With Exception Handling
Built-in Exception :
● ArithmeticError itself is not raised directly but can be used to catch exceptions from its
subclasses like ZeroDivisionError, OverflowError.
● In Python, ArithmeticError is the base class for all exceptions related to arithmetic operations,
including ZeroDivisionError, OverflowError.
Python Tkinter
Tkinter is the standard GUI (Graphical User Interface) toolkit that comes with Python.It
provides a set of tools for creating graphical applications.
Advantages of Tkinter:
● Cross-platform compatibility
● User friendly
● Customization
● Event handling
● Support for widgets (it provides built in widgets like buttons,labels,textboxes etc)
● Open source
Basic Widgets in Tkinter
● Label: Display static text or images.
● Button: Create clickable buttons to trigger actions.
● Entry: Allow user input for single-line text.
● Frame: Organize widgets within a container.
● Checkbutton: Create checkboxes for boolean options.
● Radiobutton: Create radio buttons for mutually exclusive options.
● Listbox: Display a list of items for selection.
● Scrollbar: Add scrollbars to widgets like Listbox.
● Menu: Create simple menus for application navigation.
● Canvas: Draw shapes, lines, text, and images.
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 named ‘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.
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’,
useTk=1)’. To change the name of the window, you can change the className to the desired one.

mainloop()
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:
import tkinter
m = tkinter.Tk()
m.mainloop()
FIRST WINDOW USING TKINTER:
Widgets in Tkinter
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:
Syntax:
w=Label(master, option=value)

master is the parameter used to represent the parent window.


Button
To add a button in your application, this widget is used. The general syntax is:
Syntax:
w=Button(master, option=value)

Code:
import tkinter as tk
r = tk.Tk()
r.title('button')
button = tk.Button(r, text='ok', width=10)
button.pack()
r.mainloop()
Entry
It is used to input the single line text entry from the user.
CheckButton
To selectThe
buttons. anygeneral
number of options
syntax is: by displaying a number of options to a user as toggle
Syntax:
w = CheckButton(master, option=value)
RadioButton
It is used
has to offer
to choose onemulti-choice
option. Theoption to syntax
general the user.
is:It offers several options to the user and the user
Syntax:
w = RadioButton(master, option=value)

Code:
from tkinter import *
root = Tk()
Radiobutton(root, text='ok', value=1).pack()
Radiobutton(root, text='done', value=2).pack()
mainloop()
Listbox
The ListBox widget is used to display different types of items. These items must be of the same type of font
and having the same font color. The items must also be of Text type. The user can select one or more items
from the given list according to the requirement. R

Syntax:
w = Listbox(master, option=value)
Entry Widgets:

Example 1: Username And Password


Example 2: Simple Calculator
OUTPUT:
Example 3:
Example 4: display the calendar of the selected month and year
Note: Follow this link for Python Tkinter https://www.geeksforgeeks.org/python-tkinter-tutorial/

Practice more widgets:


https://www.geeksforgeeks.org/python-gui-tkinter/

project 1: simple gui calculator


https://www.geeksforgeeks.org/python-simple-gui-calculator-using-tkinter/
Thank You

You might also like