Python Programming (BCA-4sem)
Python Programming (BCA-4sem)
Unit - I
1. Introduction to Python
➔ Python is a high-level, interpreted, general-purpose programming language known
for its simplicity and readability. It's widely used in data science, web development,
automation, and scientific computing.
➔ It is popular because it is:
◆ Simple and readable
◆ Cross-platform (Windows, Mac, Linux)
◆ Has huge libraries (AI, data science, web, automation etc.)
2. Python Interpreter
➔ Python code is executed by the Python interpreter, which:
◆ Reads Python code line by line.
◆ Converts it to bytecode.
◆ Executes the bytecode.
➔ Python does not compile into machine code first. Instead, the interpreter executes
code line by line.
➔ Ways to run Python:
1️⃣ Python shell / terminal
2️⃣ Script file (.py)
3️⃣ Jupyter Notebook
1
Python Programming
★ Jupyter Notebook:
➔ An interactive web-based environment for writing and running Python code
with proper formatting:
4. Importing modules
➔ Modules contain reusable code.
➔ Example:(1)
import math
print([Link](16))
➔ Example:(2)
# Import entire module
import math
print([Link](16))
2
Python Programming
➔ Example:
# Arithmetic operators
a = 10 + 5 # Addition: 15
b = 10 - 5 # Subtraction: 5
c = 10 * 5 # Multiplication: 50
d = 10 / 3 # Division: 3.333...
e = 10 // 3 # Floor division: 3
f = 10 % 3 # Modulus: 1
g = 10 ** 2 # Exponentiation: 100
# Comparison operators
print(10 == 10) # True
print(10 != 5) # True
print(10 > 5) # True
print(10 < 5) # False
print(10 >= 10) # True
print(10 <= 5) # False
# Logical operators
print(True and False) # False
print(True or False) # True
print(not True) # False
6. Data Types
➔ Common built-ins:
x = 10 # int
y = 3.5 # float
name = "Ram" # str
flag = True # bool
nums = [1,2,3] # list
➔ Check type:
print(type(x))
➔ Example:
# Numeric types
integer_num = 10 # int
float_num = 3.14 # float
complex_num = 2 + 3j # complex
# Text type
text = "Hello World" # str
# Boolean type
is_true = True # bool
is_false = False # bool
# Sequence types
3
Python Programming
# Mapping type
my_dict = {"name": "Alice", "age": 25} # dict
# Set types
my_set = {1, 2, 3} # set (unordered, unique)
7. Type Casting
➔ Type casting is the process of converting a value from one data type to another (e.g.,
from an integer to a string). This is done using built-in constructor functions like int(),
float(), and str().
➔ Convert one type to another.
➔ Example:(1)
a = int("10")
b = float(5)
c = str(25)
➔ Example:(2)
# Explicit type conversion
x = int(3.14) # Convert to int: 3
y = float(10) # Convert to float: 10.0
z = str(100) # Convert to string: "100"
b = bool(0) # Convert to bool: False
# Checking types
print(type(x)) # <class 'int'>
print(isinstance(y, float)) # True
4
Python Programming
else:
print("Minor")
➔ Example:(2)
# if-elif-else
grade = 85
# Nested if
age = 25
if age >= 18:
if age >= 21:
print("Adult with full privileges")
else:
print("Young adult")
else:
print("Minor")
❖ loops:
★ for loop
for i in range(5):
print(i)
★ while loop
i=1
while i <= 3:
print(i)
i += 1
➔ Example:
# for loop
for i in range(5): # 0 to 4
print(i)
# while loop
count = 0
while count < 5:
print(count)
count += 1
5
Python Programming
9. pass statement
➔ Placeholder (do nothing).
➔ The pass statement in Python is a null operation; nothing happens when it executes.
Its primary use is as a placeholder in situations where Python's syntax requires a
statement or a code block, but you don't need any actual code to run yet.
➔ Python does not allow empty code blocks. If you leave a function, loop, or conditional
statement body empty, you will get an IndentationError. The pass statement avoids
this error, allowing you to structure your code and fill in the logic later.
➔ Example:(1)
if True:
pass
➔ Example:(2)
# Placeholder for future code
def function_to_implement_later():
pass # Do nothing, prevents syntax error
class EmptyClass:
pass
if condition:
pass # Will implement logic later
➔ Example:(2)
# range(stop)
range(5) # 0, 1, 2, 3, 4
# range(start, stop)
range(2, 6) # 2, 3, 4, 5
6
Python Programming
➔ Example:(2)
# Traditional if-else
if age >= 18:
status = "Adult"
else:
status = "Minor"
# Ternary expression
status = "Adult" if age >= 18 else "Minor"
# Multiple conditions
grade = "A" if score >= 90 else "B" if score >= 80 else "C”
➔ Syntax: The syntax is different from the ?: operator found in many other languages
and reads more like natural language.
◆ Example: value_if_true if condition else value_if_false
➔ How It Works:
◆ The condition (a Boolean expression) is evaluated first.
◆ If the condition is True, the value_if_true is returned/assigned.
◆ If the condition is False, the value_if_false is returned/assigned.
➔ Example:(2)
# Basic printing
print("Hello, World!")
# Multiple items
print("Name:", "Alice", "Age:", 25)
# Changing separator
print("2023", "12", "25", sep="/") # 2023/12/25
7
Python Programming
# File output
with open("[Link]", "w") as f:
print("Saving to file", file=f)
➔ Example:(2)
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Multiple inputs
values = input("Enter two numbers separated by space: ")
a, b = map(float, [Link]())
print(f"Sum: {a + b}")
➔ Example:(2)
name = "Alice"
age = 25
height = 5.6
8
Python Programming
# 2. [Link]() method
print("Name: {}, Age: {}, Height: {:.2f}".format(name, age, height))
print("Name: {0}, Age: {1}, Height: {2:.2f}".format(name, age, height))
print("Name: {n}, Age: {a}".format(n=name, a=age))
# Formatting numbers
number = 12345.6789
print(f"Comma separated: {number:,.2f}") # 12,345.68
print(f"Percent: {0.25:.2%}") # 25.00%
print(f"Hexadecimal: {255:#x}") # 0xff
Practical Example:
# Complete example combining concepts
def calculate_grade():
"""Calculate grade based on score"""
# Validate input
if not 0 <= score <= 100:
print("Invalid score! Must be between 0 and 100.")
return
# Additional feedback
9
Python Programming
if grade == "F":
print("You need to improve!")
elif grade == "A":
print("Excellent work!")
else:
print("Good job!")
Best Practices:
1. Indentation: Always use 4 spaces (not tabs).
2. Comments: Write clear comments explaining why, not what.
3. Naming: Use descriptive variable and function names.
4. Modularity: Break code into reusable functions.
5. Error Handling: Validate user inputs.
6. Formatting: Use f-strings for modern Python code.
7. Readability: Write code that's easy to understand.
10
Python Programming
Unit - II
Data Structures and Sequences in Python
● Data Structures and Sequences:
○ Tuples,
○ lists (with slicing),
○ dictionaries, and
○ sets,
● Builtin sequence functions:
○ len(), sum(), max(), min(),
● List operations:
○ append, remove;
● dictionary value access,
● Comprehensions for lists, sets, and dictionaries to manage data collections.
★ Introduction to Sequences:
➔ Sequences are ordered collections of items.
➔ Python has several built-in sequence types.
➔ Common operations apply across different sequence types.
➔ Python provides several built-in sequence types:
◆ Tuple – fixed (unchangeable) sequence
◆ List – changeable sequence
◆ Dictionary – key–value storage
◆ Set – unordered collection of unique values
1. Tuples:
➔ A tuple is an ordered, immutable collection.
➔ Example: t = (10, 20, 30)
✔ Ordered
✔ Allows duplicates
✘ Cannot be changed
➔ Useful when data should not be modified, e.g., dates, coordinates.
➔ Access: t[1] # 20
★ Characteristics:
● Immutable (cannot be modified after creation).
● Ordered collection.
● Can contain heterogeneous data types.
● Created using parentheses () or tuple().
➔ Examples:
# Creating tuples
t1 = (1, 2, 3)
t2 = 4, 5, 6 # Parentheses are optional
t3 = (1,) # Single element tuple (comma required)
t4 = tuple([7, 8, 9])
11
Python Programming
# Accessing elements
print(t1[0]) # 1
print(t1[-1]) # 3 (last element)
# Tuple unpacking
a, b, c = t1 # a=1, b=2, c=3
2. Lists:
➔ A list is ordered and mutable.
➔ Example: lst = [5, 10, 15, 20]
➔ Slicing:
lst[1:3] # [10, 15]
lst[:2] # [5, 10]
lst[2:] # [15, 20]
lst[-1] # 20
★ Characteristics:
● Mutable (can be modified after creation).
● Ordered collection.
● Created using square brackets [] or list().
★ Basic Operations:
# Creating lists
lst1 = [1, 2, 3, 4, 5]
lst2 = list(range(5))
lst3 = ['a', 'b', 'c']
# Accessing elements
print(lst1[0]) # 1
print(lst1[-1]) # 5
# Modifying elements
lst1[0] = 10 # lst1 becomes [10, 2, 3, 4, 5]
★ Slicing:
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
12
Python Programming
★ List Methods:
lst = [1, 2, 3]
3. Dictionaries:
➔ A dictionary stores data as key : value pairs.
➔ Example: student = {"name": "Riya", "age": 18}
➔ Access values:
student["name"] # Riya
[Link]("age") # 18
➔ Keys must be unique.
★ Characteristics:
● Unordered collection of key-value pairs.
● Keys must be immutable (strings, numbers, tuples).
● Values can be of any type.
● Created using curly braces {} or dict().
★ Operations:
# Creating dictionaries
d1 = {'name': 'Alice', 'age': 25, 'city': 'NYC'}
d2 = dict(name='Bob', age=30)
d3 = dict([('name', 'Charlie'), ('age', 35)])
# Accessing values
print(d1['name']) # Alice
print([Link]('age')) # 25
print([Link]('salary', 0)) # 0 (default if key doesn't exist)
# Modifying/Adding
d1['age'] = 26 # Update value
d1['salary'] = 50000 # Add new key-value pair
# Dictionary methods
13
Python Programming
# Removing elements
del d1['city'] # Remove key 'city'
age = [Link]('age') # Removes and returns value
4. Sets:
➔ A set is an unordered collection of unique items.
➔ Example:
s = {1, 2, 3, 3}
print(s) # {1, 2, 3}
➔ Good for:
◆ removing duplicates.
◆ mathematical operations (union, intersection).
★ Characteristics:
● Unordered collection of unique elements.
● Mutable (but elements must be immutable).
● Created using curly braces {} or set().
● Supports mathematical set operations.
★ Operations:
# Creating sets
s1 = {1, 2, 3, 4, 5}
s2 = set([4, 5, 6, 7, 8])
s3 = set() # Empty set (NOT {} which creates empty dict)
# Set operations
union = s1 | s2 # {1, 2, 3, 4, 5, 6, 7, 8}
intersection = s1 & s2 # {4, 5}
difference = s1 - s2 # {1, 2, 3}
symmetric_diff = s1 ^ s2 # {1, 2, 3, 6, 7, 8}
# Set methods
[Link](6) # {1, 2, 3, 4, 5, 6}
[Link](3) # {1, 2, 4, 5, 6}
[Link](10) # No error if element not present
14
Python Programming
➔ Example:(1)
data = [1, 2, 3, 4, 5]
➔ Example:(2)
nums = [5, 10, 15]
len(nums) # 3
sum(nums) # 30
max(nums) # 15
min(nums) # 5
1. append()
➔ The append() method adds elements at the end of the list. This method can
only add a single element at a time. You can use the append() method inside
a loop to add multiple elements.
➔ Example:
15
Python Programming
2. remove()
➔ The remove() method removes an element from the list. Only the first
occurrence of the same element is removed in the case of multiple
occurrences.
➔ Example:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link]('makes learning fun!')
print(myList)
● Output: [ 1, 2, 3, ‘EduCBA’ ]
🕯️ Comprehensions:
➔ Python, comprehension is a concise way to create a new list, set, or dictionary based
on an existing iterable object.
➔ Comprehensions are more concise and readable than traditional looping constructs
such as for and while loops, and they can often be more efficient as well.
➔ Comprehensions in Python provide a concise and efficient way to create new
sequences from existing ones.
➔ They enhance code readability and reduce the need for lengthy loops.
16
Python Programming
1. List Comprehensions:
➔ List comprehensions allow for the creation of lists in a single line, improving efficiency
and readability. They follow a specific pattern to transform or filter data from an
existing iterable.
➔ Syntax: [expression for item in iterable if condition]
Where:
expression: Operation applied to each item.
item: Variable representing the element from the iterable.
iterable: The source collection.
condition (optional): A filter to include only specific items.
➔ Example:(1)
# Basic syntax: [expression for item in iterable if condition]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
# Nested comprehensions
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Set Comprehensions:
➔ Set Comprehensions are similar to list comprehensions but result in sets,
automatically eliminating duplicate values while maintaining a concise syntax.
➔ Syntax: {expression for item in iterable if condition}
Where:
expression: The operation applied to each item.
17
Python Programming
➔ Example:(1)
# Similar to list comprehensions but with curly braces
3. Dictionary Comprehensions:
➔ Dictionary Comprehensions are used to construct dictionaries in a compact form,
making it easy to generate key-value pairs dynamically based on an iterable.
➔ Syntax: {key_expression: value_expression for item in iterable if condition}
Where:
key_expression: Determines the dictionary key.
value_expression: Computes the value.
iterable: The source collection.
condition (optional): Filters elements before adding them.
➔ Example:(1)
# Syntax: {key_expr: value_expr for item in iterable if condition}
# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
18
Python Programming
❖ Benefits:
➢ shorter
➢ faster
➢ more readable
Practical Examples:
# Example 1: Student records
students = [
{'id': 1, 'name': 'Alice', 'grades': [85, 90, 78]},
{'id': 2, 'name': 'Bob', 'grades': [92, 88, 95]}
]
19
Python Programming
Unit - III
Functions, Generators & NumPy
● Defining functions,
● namespaces, scope,
● local functions,
● multiple return values,
● Anonymous (lambda) functions,
● partial argument application,
● generators,
● NumPy: Ndimensional arrays,
● arithmetic operations,
● indexing, slicing,
● pseudorandom number generation, and
● array operations (sum, mean).
1. Defining Functions
➔ A function is a block of reusable code that performs a specific task.
➔ Syntax:
def function_name(parameters):
statement
return value
➔ Example:(1)
def add(a, b):
return a + b
result = add(5, 3)
print(result)
➔ Example:(2)
def function_name(parameters):
"""Docstring (optional)"""
# Function body
return value
# Example:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
2. Namespaces
➔ A namespace is a container that holds names of variables, functions, and objects.
★ Types of Namespaces:
1. Local Namespace – inside a function
2. Global Namespace – outside all functions
3. Built-in Namespace – predefined names in Python
20
Python Programming
➔ Example:
x = 10 # global namespace
def show():
y = 5 # local namespace
print(y)
3. Scope
➔ Scope defines where a variable can be accessed.
★ Types of Scope:
○ Local Scope
○ Global Scope
➔ Example:
x = 20
def test():
print(x) # global variable accessible
test()
outer()
➔ Example:(2)
def outer_function(x):
def inner_function(y):
return y * 2
return inner_function(x) + 5
result = outer_function(10) # 25
21
Python Programming
➔ Example:(2)
def get_coordinates():
x = 10
y = 20
z = 30
return x, y, z # Returns a tuple
# Unpacking
a, b, c = get_coordinates()
➔ Example:(2)
# Syntax: lambda arguments: expression
square = lambda x: x ** 2
add = lambda a, b: a + b
22
Python Programming
double = partial(multiply, 2)
print(double(5))
➔ Example:(2)
from functools import partial
# Fix exponent to 2
square = partial(power, exponent=2)
print(square(5)) # 25
# Fix base to 2
power_of_two = partial(power, base=2)
print(power_of_two(3)) # 8
# A normal function
def f(a, b, c, x):
return 1000*a + 100*b + 10*c + x
# Calling g()
print(g(5))
➢ Output: 3145
➔ Example:(2)
➢ In the example, we have used pre-defined value constant values in which we
have assigned the values of c and b and add_part() takes a single argument
i.e. the variable a.
23
Python Programming
# A normal function
def add(a, b, c):
return 100 * a + 10 * b + c
➢ Output: 312
8. Generators
➔ Generators produce values one at a time using yield.
➔ In Python, a generator is a function that returns an iterator that produces a sequence
of values when iterated over.
➔ Generators are useful when we want to produce a large sequence of values, but we
don't want to store all of them in memory at once.
➔ Example:(1)
def numbers():
for i in range(3):
yield i
➔ Example:(2)
24
Python Programming
# Generator function
def count_up_to(n):
i=1
while i <= n:
yield i # Pauses here
i += 1
# Generator expression
squares = (x**2 for x in range(10))
# Usage
for num in count_up_to(5):
print(num) # 1, 2, 3, 4, 5
★ Advantages:
➢ Saves memory.
➢ Faster execution
★ Creating Array:
import numpy as np
★ 2-D Array:
arr2 = [Link]([[1,2],[3,4]])
➔ Example:
import numpy as np
# Creating arrays
arr1 = [Link]([1, 2, 3]) # 1D
arr2 = [Link]([[1, 2], [3, 4]]) # 2D
arr3 = [Link]((3, 3)) # 3x3 zeros
25
Python Programming
print(a + b)
print(a * b)
➔ Example:(2)
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
# Element-wise operations
print(a + b) # [5 7 9]
print(a - b) # [-3 -3 -3]
print(a * b) # [4 10 18]
print(a / b) # [0.25 0.4 0.5]
print(a ** 2) # [1 4 9]
# Matrix multiplication
mat1 = [Link]([[1, 2], [3, 4]])
mat2 = [Link]([[5, 6], [7, 8]])
print([Link](mat1, mat2))
# [[19 22]
# [43 50]]
print(arr[1])
print(arr[1:4])
➔ Example:(2)
arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
26
Python Programming
# Indexing
print(arr[0, 1]) #2
print(arr[2, 2]) #9
# Slicing
print(arr[0:2, :]) # First two rows
# [[1 2 3]
# [4 5 6]]
# Boolean indexing
mask = arr > 5
print(arr[mask]) # [6 7 8 9]
➔ Example:(2)
# Random module
[Link](42) # For reproducibility
# Integers in range
random_ints = [Link](0, 10, size=5)
# Normal distribution
normal_nums = [Link](loc=0, scale=1, size=5)
# Random choice
27
Python Programming
# Shuffle
arr = [Link](10)
[Link](arr)
★ Characteristics of PRNG:
● Efficient: PRNG can produce many numbers in a short time and is advantageous for
applications that need many numbers
● Deterministic: A given sequence of numbers can be reproduced at a later date if the
starting point in the sequence is [Link] is handy if you need to replay
the same sequence of numbers again at a later stage.
● Periodic: PRNGs are periodic, which means that the sequence will eventually repeat
itself. While periodicity is hardly ever a desirable characteristic, modern PRNGs have
a period that is so long that it can be ignored for most practical purposes
★ Applications of PRNG:
➔ PRNGs are suitable for applications where many random numbers are required and
where it is useful that the same sequence can be replayed easily. Popular examples
of such applications are simulation and modeling applications. PRNGs are not
suitable for applications where it is important that the numbers are really
unpredictable, such as data encryption and gambling.
print([Link](arr))
print([Link](arr))
➔ Example:(2)
arr = [Link]([[1, 2, 3], [4, 5, 6]])
# Aggregations
print([Link](arr)) # 21
print([Link](arr)) # 3.5
print([Link](arr)) #1
28
Python Programming
print([Link](arr)) #6
print([Link](arr)) # Standard deviation
print([Link](arr)) # Variance
# Axis-wise operations
print([Link](arr, axis=0)) # Column sums: [5 7 9]
print([Link](arr, axis=1)) # Row sums: [6 15]
29
Python Programming
Unit - IV
Pandas (Series, DataFrames & Data Handling)
● Series,
● DataFrames, reading CSV files,
● DataFrame operations: head(), tail(), info(), shape, reshape(), columns,
● Handling Missing Data: isnull(), dropna(),
● Statistical Functions: mean(), sum(), describe(), value_counts(), corr(),
● Data Selection and Indexing: loc, iloc,
● Apply Function: apply,
● Data Filtering and Sorting: Data filtering, sorting,
● Basic Data Cleaning: basic data cleaning.
❖ Pandas:
➔ Pandas, a powerful Python library used for data analysis and manipulation.
➔ It mainly works with two data structures: Series and DataFrame.
➔ [NOTE: This unit helps students understand how to efficiently manage, analyze, and
clean real-world data using Pandas, which is essential for data science, machine
learning, and software development.]
1. Series
➔ A Series is a one-dimensional labeled array that can hold data like integers, floats,
strings, or Python objects. Each value in a Series has an index.
➔ Example use: storing marks of students or daily temperature values.
➔ Creating Series:
import pandas as pd
import numpy as np
# From list
s1 = [Link]([1, 3, 5, [Link], 6, 8])
# From dictionary
s2 = [Link]({'A': 10, 'B': 20, 'C': 30})
2. DataFrame
➔ A DataFrame is a two-dimensional data structure similar to a table or spreadsheet. It
consists of rows and columns, where each column can contain different data types.
DataFrames are widely used for handling large datasets.
➔ Creating DataFrames:
# From dictionary
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['NYC', 'LA', 'Chicago']
})
30
Python Programming
➔ Basic Inspection:
[Link](3) # First n rows (default 5)
[Link](3) # Last n rows (default 5)
[Link]() # Summary of DataFrame
[Link] # Returns (rows, columns)
[Link] # Column names
[Link] # Data types of each column
[Link]() # Statistical summary
31
Python Programming
6. Statistical Functions
● mean(): Calculates the average of values in a column.
● sum(): Calculates the total sum of values.
● describe(): Provides a summary of statistics such as count, mean, standard
deviation, min, and max.
● value_counts(): Counts unique values in a column and shows their frequency.
● corr(): Finds the correlation between numerical columns, useful for understanding
relationships in data.
➔ Example:
[Link]() # Column-wise mean
[Link]() # Column-wise sum
[Link]() # Minimum values
[Link]() # Maximum values
[Link]() # Standard deviation
[Link]() # Median values
[Link]() # Count non-null values
[Link]() # Correlation matrix
df['Column'].value_counts() # Frequency of unique values
➔ Example:
# Column selection
df['Column'] # Single column (returns Series)
df[['Col1', 'Col2']] # Multiple columns (returns DataFrame)
8. Apply Function
➔ The apply() function is used to apply a custom function to rows or columns of a
DataFrame. This is helpful for data transformation and feature creation.
32
Python Programming
➔ Example:
# Using apply()
df['New_Col'] = df['Column'].apply(lambda x: x*2)
df['Category'] = df['Age'].apply(lambda x: 'Young' if x < 30 else 'Adult')
➔ Data Filtering:
# Boolean indexing
df[df['Age'] > 25] # Simple condition
df[(df['Age'] > 25) & (df['City'] == 'NYC')] # Multiple conditions
df[df['Name'].[Link]('Al')] # String contains
df[df['Column'].isin(['A', 'B', 'C'])] # Value in list
➔ Sorting:
df.sort_values('Age') # Sort by column
df.sort_values('Age', ascending=False) # Descending order
df.sort_values(['Col1', 'Col2']) # Sort by multiple columns
df.sort_index() # Sort by index
# 3. Remove outliers
Q1 = df['Column'].quantile(0.25)
Q3 = df['Column'].quantile(0.75)
IQR = Q3 - Q1
df = df[~((df['Column'] < (Q1 - 1.5 * IQR)) |
(df['Column'] > (Q3 + 1.5 * IQR)))]
33
Python Programming
# 5. Reset index
df = df.reset_index(drop=True)
return df
➔ Reshaping Data:
# Pivot tables
pivot = df.pivot_table(values='Value',
index='Date',
columns='Category',
aggfunc='mean')
# Melt (unpivot)
melted = [Link](df, id_vars=['ID'],
value_vars=['Jan', 'Feb', 'Mar'],
var_name='Month',
value_name='Sales')
# Stack/Unstack
stacked = [Link]() # Move column labels to index
unstacked = [Link]() # Move index labels to columns
34
Python Programming
Unit-V
Data Visualization, Libraries, Error Handling, File I/O & Flask
● Data Visualization using Matplotlib: Line plots, bar plots, histograms, scatter plots,
subplots, custom labels.
● Overview of Scientific Libraries: Scikitlearn, SciPy, NetworkX.
● Error handling: NameError, TypeError, ValueError with try, except, finally.
● File I/O: reading/writing text files.
● Web development with Flask.
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
[Link](x, y)
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Line Plot Example")
[Link]()
[Link](subjects, marks)
[Link]("Bar Plot")
[Link]()
35
Python Programming
(c) Histogram
➔ A histogram shows the frequency distribution of numerical data.
➔ Uses: Data distribution analysis.
➔ Example: Age distribution of people.
➔ Example:
import [Link] as plt
x = [1, 2, 3, 4]
y = [5, 7, 6, 8]
[Link](x, y)
[Link]("Scatter Plot")
[Link]()
(e) Subplots
➔ Subplots allow multiple plots in a single figure.
➔ Uses: Comparing multiple visualizations together
➔ Example:
import [Link] as plt
[Link](1, 2, 1)
[Link]([1, 2, 3], [4, 5, 6])
[Link]("Plot 1")
[Link](1, 2, 2)
[Link]([1, 2, 3], [3, 7, 5])
[Link]("Plot 2")
[Link]()
36
Python Programming
◆ X-axis label
◆ Y-axis label
◆ Legend
➔ These improve readability and understanding of graphs.
(a) Scikit-learn
➔ Scikit-learn is a machine learning library used for:
◆ Classification
◆ Regression
◆ Clustering
◆ Model evaluation
➔ It provides simple and efficient tools for data analysis and predictive modeling.
➔ Example: from sklearn.linear_model import LinearRegression
(b) SciPy
➔ SciPy is used for scientific and mathematical computations.
➔ Main features:
◆ Linear algebra
◆ Integration
◆ Optimization
◆ Statistics
◆ Signal and image processing
(c) NetworkX
➔ NetworkX is used to create and analyze graphs and networks.
➔ Applications:
◆ Social networks
◆ Computer networks
◆ Transportation systems
37
Python Programming
★ Common Errors:
● NameError: When a variable is not defined
● TypeError: When an operation is applied to incompatible data types
● ValueError: When a function receives an argument of correct type but invalid value
@[Link]("/")
def home():
return "Welcome to Flask Web App"
[Link]()
38
Python Programming
★ Features:
● Simple and flexible
● Built-in development server
● URL routing
● Template support
★ Uses:
● Creating web applications
● APIs
● Small to medium-scale projects
Summary:
● Plots → Data visualization using Matplotlib
● Scikit-learn → Machine Learning
● SciPy → Scientific computing
● NetworkX → Graph analysis
● try-except-finally → Error handling
● File I/O → Read/write files
● Flask → Python web framework
39