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

Unit-5 a Notes Python 2024-25.docx

Important notes python , unit 5

Uploaded by

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

Unit-5 a Notes Python 2024-25.docx

Important notes python , unit 5

Uploaded by

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

Python Programming (BCC302)

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.

What is package? Explain various packages in python programming with


example.
In Python, a package is essentially a collection of modules organized in a directory structure, making
it easier to organize and manage code.

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.

Creating and Using Packages in Python

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.

Example of a Simple Package Structure


We have a project that needs mathematical and string operations. We can organize these into a package
called utilities.

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

1. math_ops.py (Math operations module):


def add(a, b):
return a + b

def subtract(a, b):


return a - b
2. string_ops.py (String operations module):
def to_uppercase(s):
return s.upper()

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 1


def to_lowercase(s):
return s.lower()
3. init .py (Package initializer):

# 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

# Using functions from math_ops module


print(add(5, 3)) # Output: 8
print(subtract(5, 3)) # Output: 2

# Using functions from string_ops module


print(to_uppercase("hello")) # Output: HELLO
print(to_lowercase("WORLD")) # Output: world

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

Import and use package in python program

Types of Packages in Python

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

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 2


2. Third-Party Packages

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.

Benefits of Using Packages

 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.

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 3


In Python, packages like Matplotlib, NumPy, and Pandas provide a wide range of built-in functions
that make data manipulation, numerical operations, and visualization easier.

1. Matplotlib

Matplotlib is primarily used for data visualization, allowing you to create a wide variety of static,
animated, and interactive plots.

Commonly Used Functions in matplotlib.pyplot


 plot(): Creates a line plot.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
 scatter(): Creates a scatter plot for visualizing relationships between two variables.
plt.scatter([1, 2, 3], [4, 5, 6])
plt.show()
 bar(): Creates a bar chart, useful for categorical data comparison.
plt.bar(['A', 'B', 'C'], [4, 7, 1])
plt.show()
 hist(): Creates a histogram for showing frequency distributions of data.
data = [1, 1, 2, 3, 3, 3, 4, 4, 5]
plt.hist(data, bins=5)
plt.show()
 xlabel() / ylabel() / title(): Sets labels for the x-axis, y-axis, and the title of the plot.
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Line Plot")
plt.show()
 legend(): Adds a legend to the plot.
plt.plot([1, 2, 3], [4, 5, 6], label="Line 1")
plt.legend()
plt.show()
 savefig(): Saves the plot as an image file.
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig("plot.png")

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

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 4


 Mathematical Functions:
o mean(): Computes the mean of elements.
o median(): Computes the median.
o std(): Computes the standard deviation.
data = np.array([1, 2, 3, 4, 5])
np.mean(data) # 3.0
np.median(data) # 3.0
np.std(data) # 1.41 (approx.)
 sum(): Returns the sum of elements.
np.sum(arr)
 dot(): Computes the dot product of two arrays.
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
np.dot(arr1, arr2) # Output: 11 (1*3 + 2*4)
 Random Functions:
o random.rand(): Generates an array of random values between 0 and 1.
o random.randint(): Generates random integers within a specified range.
np.random.rand(3) # Array of 3 random numbers
np.random.randint(1, 10) # Random integer between 1 and 9

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.

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.

What Can Pandas Do?


Pandas gives you answers about the data. Like:
 Is there a correlation between two or more columns?
 What is average value?
 Max value?
 Min value?
Pandas are also able to delete rows that are not relevant, or contains wrong values, like empty or
NULL values. This is called cleaning the data.

Example-1
import pandas
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 5


Example-2
import pandas as pd

mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pd.DataFrame(mydataset)
print(myvar)

Example-3

import pandas as pd
print(pd. version )

Read CSV Files

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())

Note: use to_string() to print the entire DataFrame.


If you have a large DataFrame with many rows, Pandas will only return the first 5 rows, and the last
5 rows:

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)

Commonly Used Functions in pandas


 DataFrame(): Creates a DataFrame, the primary data structure in Pandas.
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [24, 27, 22]
})
 read_csv(): Reads a CSV file into a DataFrame.
df = pd.read_csv("data.csv")

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 6


 head() / tail(): Shows the first or last few rows of the DataFrame.
df.head() # First 5 rows
df.tail() # Last 5 rows
 describe(): Generates summary statistics for numerical columns.
df.describe()
 loc[] and iloc[]: Used to access rows and columns by label or by index.
# Access by label
df.loc[0, 'Name'] # Accesses first row, 'Name' column

# Access by index position


df.iloc[0, 1] # Accesses first row, second column

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')

 groupby(): Groups data by a specified column and can perform aggregation.


df.groupby('Age').mean()
 drop(): Drops specified rows or columns.
df = df.drop('Age', axis=1) # Drops the 'Age' column
 merge(): Merges two DataFrames based on common columns.
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 2], 'Score': [88, 95]})
merged_df = pd.merge(df1, df2, on='ID')
 Data Cleaning Functions:
o fillna(): Replaces NaN values with specified values.
o dropna(): Drops rows or columns with NaN values.
df.fillna(0) # Replaces NaN with 0
df.dropna() # Drops rows with NaN values

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 7


Summary Table of Functions
Package Function Description
Matplotlib plot() Creates a line plot.
scatter() Creates a scatter plot.
bar() Creates a bar chart.
hist() Creates a histogram.
xlabel(), ylabel() Sets axis labels.
legend(), title() Adds legend and title.
NumPy array() Creates an array.
arange(), linspace() Generates arrays of ranges or equally spaced values.
mean(), std() Computes mean and standard deviation.
random.rand(), randint() Generates random values or integers.
Pandas DataFrame() Creates a DataFrame.
read_csv() Reads a CSV into a DataFrame.
head(), tail() Shows the first/last few rows.
groupby() Groups data and performs aggregation.
drop(), merge() Drops columns or merges DataFrames.
fillna(), dropna() Fills or drops NaN values for data cleaning.

Each of these packages adds powerful functionality to Python, enabling users to perform complex data
manipulation, visualization, and analysis tasks with ease.

Python Programming, Dr B.K. Saraswat, CSE, RKGIT 8

You might also like