Unit-5 a Notes Python 2024-25.docx
Unit-5 a Notes Python 2024-25.docx
Unit-V
Python packages:
Simple programs using the built-in functions of packages matplotlib, numpy, pandas etc.
GUI Programming: Tkinter introduction, Tkinter and PythonProgramming, Tk Widgets, Tkinter
examples. Python programming with IDE.
Packages allow us to logically arrange and reuse code across different projects. They are especially
useful in large programs where the codebase can be modularized into smaller, reusable components.
A package is created by organizing multiple related modules (Python files) in a directory, and the
directory typically includes a special “ init .py” file, which tells Python that this directory is a
package. This file can be empty or contain code to initialize the package.
project_folder/
│
├── utilities/ # Package directory
│ ├── init .py # Initializes the package
│ ├── math_ops.py # Module for math operations
│ └── string_ops.py # Module for string operations
└── main.py # Main script to use the package
# This file can be empty, or you can import specific functions or modules
from .math_ops import add, subtract
from .string_ops import to_uppercase, to_lowercase
Using the Package
Now, in main.py, we can import and use functions from our utilities package.
# Importing functions from the utilities package
from utilities import add, subtract, to_uppercase, to_lowercase
Example
To create a package in a project
Project > New Package >“MyPackage”
An automatic file be created in MyPackage by name : “ init .py ”
Create a python file name “addsub.py”
Write following code in the “addsub.py”
def add(a,b):
return a+b
def sub(a,b):
return a-b
Now initialise the file “addsub.py” in the “ init .py ”
Write following code in “ init .py ” for inisialising the the file “addsub.py
from .addsub import add, sub
Now create a main file in project where you want to use your created package name
“MyPackage”
Import MyPackage import add, sub
Python has a variety of package types based on their use cases. Here are some common ones:
1. Standard Library Packages
o Python’s standard library includes many built-in packages, such as os, sys, math, json,
and datetime.
o These provide a wide range of functions, from file handling to mathematical
calculations and more.
Example:
import os
print(os.getcwd()) # Prints the current working directory
o Python has a rich ecosystem of third-party packages available through the Python
Package Index (PyPI). Some popular third-party packages include requests (for HTTP
requests), pandas (for data manipulation), and numpy (for numerical computing).
Example:
import requests
response = requests.get("https://api.example.com/data")
print(response.json())
3. Custom Packages
o Custom packages are user-defined packages, like our utilities example. They are useful
for organizing project-specific code into reusable modules.
4. Namespace Packages
o Introduced in Python 3, namespace packages allow for the creation of packages without
an init .py file. These packages are often used for large, multi-part projects where
sub-packages can be spread across multiple directories.
Example:
# Namespace packages typically follow a larger modular structure and can be
# found in projects with large codebases, like web frameworks or toolkits.
Code Organization: Grouping similar functionality makes code easier to manage and
understand.
Reusability: Common functionalities can be reused across different projects or files.
Modularity: Modular code is easier to maintain and test.
Python packages help developers structure their code effectively, making large programs more
manageable and enabling code reuse across projects.
Explain built-in functions of packages matplotlib, numpy, pandas etc in python programming.
NumPy:
A fundamental package for scientific and mathematical computing that supports large
arrays and matrices.
Pandas:
A package for records manipulation and analysis.
Matplotlib:
A package for records visualization.
TensorFlow:
A package for deep analysis.
Pytest:
A framework for finding bugs.
Requests:
An HTTP library for Python.
Docutils:
A package that creates tools for processing plaintext documents into other formats.
Setuptools:
A package that handles third-party packages.
1. Matplotlib
Matplotlib is primarily used for data visualization, allowing you to create a wide variety of static,
animated, and interactive plots.
2. NumPy
NumPy is a library for numerical operations and is especially efficient for handling large arrays and
matrices.
Commonly Used Functions in numpy
array(): Creates a NumPy array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arange(): Generates an array with a specified range and step.
arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace(): Generates an array of evenly spaced values over a specified interval.
arr = np.linspace(0, 1, 5) # [0., 0.25, 0.5, 0.75, 1.]
reshape(): Reshapes an array to a different dimension.
arr = np.arange(6).reshape(2, 3) # Reshapes to 2x3 array
3. Pandas
What is Pandas?
Pandas is a data manipulation library that provides data structures for efficient storage and
manipulation of data. It is particularly useful for handling structured data and performing analysis on
it.
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.
Example-1
import pandas
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pd.DataFrame(mydataset)
print(myvar)
Example-3
import pandas as pd
print(pd. version )
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'.
Example-4
import pandas as pd
df = pd.read_csv('data.csv')
print(df.to_string())
Example-5
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Example-6
import pandas as pd
print(pd.options.display.max_rows)
Example
import pandas as pd
df = pd.read_csv('d:\\data.csv')
df.loc[0:4]
value_counts()
import pandas as pd
df = pd.read_csv('d:\\data.csv')
df["Duration"].value_counts()
drop_duplicates()
import pandas as pd
df = pd.read_csv('d:\\data.csv')
df.drop_duplicates("Duration")
or df.drop_duplicates(inplace=True)
sort_values()
import pandas as pd
df = pd.read_csv('d:\\data.csv')
df.sort_values(by='Duration')
Each of these packages adds powerful functionality to Python, enabling users to perform complex data
manipulation, visualization, and analysis tasks with ease.