0% found this document useful (0 votes)
3 views17 pages

Python Practical File-1

The document outlines practical experiments for a Data Science course, covering string manipulation, list operations, DataFrame transposition, NumPy matrix creation, and DataFrame operations like merging, grouping, and concatenation. Each experiment includes objectives, theoretical background, program code, and expected output. The content is structured to provide hands-on experience with Python programming and data manipulation techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Python Practical File-1

The document outlines practical experiments for a Data Science course, covering string manipulation, list operations, DataFrame transposition, NumPy matrix creation, and DataFrame operations like merging, grouping, and concatenation. Each experiment includes objectives, theoretical background, program code, and expected output. The content is structured to provide hands-on experience with Python programming and data manipulation techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 1 : Reverse a String

Objective:
Write a Python program to reverse a string. The program should accept a string from the user and display its reverse.

Theory:
In Python, strings are sequences and support slicing. The slice notation s[::-1] reverses a string by stepping backward through each character.
Python also provides the reversed() built-in and manual loop approaches.

Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
user_input = "Hello"
print('Enter a string:', user_input)
reversed_slice = user_input[::-1]
print('Reversed using slicing:', reversed_slice)
reversed_builtin = ''.join(reversed(user_input))
print('Reversed using reversed() :', reversed_builtin)
result = ''
for ch in user_input:
result = ch + result
print('Reversed using loop:', result)

Output:

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
Enter a string: Hello
Reversed using slicing: olleH
Reversed using reversed() : olleH
Reversed using loop: olleH

Page 1
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 2 : List Operations — Append, Compare, Convert to Dictionary

Objective:
Perform the following operations on Python lists: (a) Append an element, (b) Compare two lists, (c) Convert a list to a dictionary.

Theory:
Python lists are mutable, ordered sequences. The append() method adds an element at the end. Lists can be compared using relational operators
(==, <, >). A list can be converted to a dictionary using dict() with paired tuples, or zip() to combine two lists into key-value pairs.

(a) Append Element


Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
my_list = [10, 20, 30, 40]
print('Original List:', my_list)
element = 60
print('Enter element to append:', element)
my_list.append(element)
print('List after append:', my_list)

Output:

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
Original List: [10, 20, 30, 40]
Enter element to append: 60
List after append: [10, 20, 30, 40, 60]

(b) Compare Two Lists


Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 4, 5]
list3 = [5, 4, 3, 2, 1]
print('List 1:', list1)
print('List 2:', list2)
print('List 3:', list3)
print('\nList1 == List2 :', list1 == list2)
print('List1 == List3 :', list1 == list3)
print('List1 < List3 :', list1 < list3)
print('List1 > List3 :', list1 > list3)

Output:

Page 2
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
List 1: [1, 2, 3, 4, 5]
List 2: [1, 2, 3, 4, 5]
List 3: [5, 4, 3, 2, 1]

List1 == List2 : True


List1 == List3 : False
List1 < List3 : True
List1 > List3 : False

(c) Convert List to Dictionary


Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
keys = ['name', 'age', 'city', 'branch']
values = ['Kunal', 21, 'Gwalior', 'CSE-DS']
my_dict = dict(zip(keys, values))
print('Keys :', keys)
print('Values :', values)
print('Dictionary:', my_dict)
print('\nKey-Value pairs:')
for k, v in my_dict.items():
print(f' {k} --> {v}')

Output:

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
Keys : ['name', 'age', 'city', 'branch']
Values : ['Kunal', 21, 'Gwalior', 'CSE-DS']
Dictionary: {'name': 'Kunal', 'age': 21, 'city': 'Gwalior', 'branch': 'CSE-DS'}

Key-Value pairs:
name --> Kunal
age --> 21
city --> Gwalior
branch --> CSE-DS

Page 3
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 3 : Transpose a Pandas DataFrame

Objective:
Write a program to transpose a Pandas DataFrame. Transposing swaps rows and columns of a table.

Theory:
Pandas provides the .T attribute (or transpose() method) to flip a DataFrame over its main diagonal, making rows into columns and vice versa.
This is commonly used in data reshaping and pivot operations.

Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import pandas as pd
data = {
'Student': ['Kunal', 'Arjun', 'Hemant', 'Ankit'],
'Math': [85, 78, 92, 88],
'Science': [90, 82, 76, 95],
'English': [75, 88, 84, 79],
}
df = [Link](data)
print('Original DataFrame (rows = students):')
print(df)
print('Shape:', [Link], ' (rows, columns)\n')
df_T = df.T
print('Transposed DataFrame (rows = subjects):')
print(df_T)
print('Shape after Transpose:', df_T.shape)

Output:

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
Original DataFrame (rows = students):
Student Math Science English
0 Kunal 85 90 75
1 Arjun 78 82 88
2 Hemant 92 76 84
3 Ankit 88 95 79
Shape: (4, 4) (rows, columns)

Transposed DataFrame (rows = subjects):


0 1 2 3
Student Kunal Arjun Hemant Ankit
Math 85 78 92 88
Science 90 82 76 95
English 75 88 84 79
Shape after Transpose: (4, 4)

Page 4
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 4 : NumPy 3×3 Matrix (Values 2–10)

Objective:
Write a NumPy program to create a 3×3 matrix with values ranging from 2 to 10.

Theory:
NumPy's arange() generates evenly spaced values in a given range. The reshape() method changes the array's shape without altering data. A 1D
array of 9 elements (2–10) can be reshaped into a 3×3 matrix.

Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import numpy as np
arr = [Link](2, 11)
print('1D Array:', arr)
matrix = [Link](3, 3)
print('\n3x3 Matrix:')
print(matrix)
print('\nMatrix Properties:')
print('Shape (rows, cols) :', [Link])
print('Data type :', [Link])
print('Minimum value :', [Link]())
print('Maximum value :', [Link]())
print('Sum of all elements:', [Link]())
print('Average (Mean):', [Link]())

Output:

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
1D Array: [ 2 3 4 5 6 7 8 9 10]

3x3 Matrix:
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]

Matrix Properties:
Shape (rows, cols) : (3, 3)
Data type : int64
Minimum value : 2
Maximum value : 10
Sum of all elements: 54
Average (Mean): 6.0

Page 5
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 5 : DataFrame Operations — Merge, Group, Concatenate

Objective:
Perform Merge, Grouping, and Concatenation operations on Pandas DataFrames.

Theory:
[Link]() combines DataFrames based on a common key column, similar to SQL JOIN operations (inner, left, right, outer). groupby() splits data
into groups based on some criteria, applies aggregation functions, and combines results — the split-apply-combine paradigm. [Link]() stacks
DataFrames along an axis. axis=0 (default) stacks row-wise (vertically); axis=1 stacks column-wise (horizontally).

(a) Merging Two DataFrames


Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import pandas as pd
employees = [Link]({
'EmpID': [101, 102, 103, 104],
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'DeptID': [1, 2, 1, 3],
})
departments = [Link]({
'DeptID': [1, 2, 3],
'DeptName': ['Engineering', 'Marketing', 'Finance'],
})
merged_inner = [Link](employees, departments, on='DeptID', how='inner')
print('Inner Merge Result:')
print(merged_inner)
merged_left = [Link](employees, departments, on='DeptID', how='left')
print('\nLeft Merge Result:')
print(merged_left)

Output:

Name
Name :: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :: 0905CD241045
0905CD241020
----------------------------------------
Inner Merge Result:
EmpID Name DeptID DeptName
0 101 Alice 1 Engineering
1 102 Bob 2 Marketing
2 103 Charlie 1 Engineering
3 104 David 3 Finance

Left Merge Result:


EmpID Name DeptID DeptName
0 101 Alice 1 Engineering
1 102 Bob 2 Marketing
2 103 Charlie 1 Engineering
3 104 David 3 Finance

(b) Grouping Operations


Program Code:

Page 6
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import pandas as pd
sales = [Link]({
'Region': ['North', 'South', 'North', 'East', 'South', 'East'],
'Product': ['A', 'B', 'B', 'A', 'A', 'B'],
'Sales': [200, 150, 300, 180, 250, 220],
'Units': [20, 15, 30, 18, 25, 22],
})
region_summary = [Link]('Region').agg(
Total_Sales=('Sales', 'sum'),
Avg_Sales=('Sales', 'mean'),
Total_Units=('Units', 'sum'),
).reset_index()
print('Sales Summary by Region:')
print(region_summary)

Output:

Name
Name :: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :: 0905CD241045
0905CD241020
----------------------------------------
Sales Summary by Region:
Region Total_Sales Avg_Sales Total_Units
0 East 400 200.0 40
1 North 500 250.0 50
2 South 400 200.0 40

(c) Concatenating DataFrames


Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import pandas as pd
df1 = [Link]({
'Name': ['Arjun', 'Kunal'],
'Score': [88, 75],
})
df2 = [Link]({
'Name': ['Ankit', 'Hemant'],
'Score': [92, 85],
})
concat_v = [Link]([df1, df2], axis=0, ignore_index=True)
print('Vertical Concatenation (rows stacked):')
print(concat_v)
concat_h = [Link]([df1, df2], axis=1)
print('\nHorizontal Concatenation (columns side by side):')
print(concat_h)

Output:

Page 7
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
Vertical Concatenation (rows stacked):
Name Score
0 Arjun 88
1 Kunal 75
2 Ankit 92
3 Hemant 85

Horizontal Concatenation (columns side by side):


Name Score Name Score
0 Arjun 88 Ankit 92
1 Kunal 75 Hemant 85

Page 8
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 6 : Regular Expression Pattern Matching

Objective:
Write a Python program to check if a regular expression pattern matches a given string using the re module.

Theory:
Python's built-in re module provides regular expression support. Key functions: [Link]() — matches at the beginning; [Link]() — anywhere in
the string; [Link]() — entire string; [Link]() — all occurrences.

Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import re
user_text = "Kunal scored 95 marks"
user_pat = r'\d+'
print('Enter the string to test :', user_text)
print('Enter the regex pattern :', user_pat)
match = [Link](user_pat, user_text)
if match:
print(f'MATCH FOUND : "{[Link]()}" at position {[Link]()}')
else:
print('NO MATCH FOUND')
print('\n--- Preset Pattern Demos ---')
m = [Link](r'\d+', 'Phone: 9876543210')
print('Find digits:', [Link]() if m else 'No match')
m = [Link](r'[a-zA-Z]+', '123 Hello 456')
print('Find a word:', [Link]() if m else 'No match')
m = [Link](r'^[A-Z]', 'Kunal kumar')
print('Starts with caps :', [Link]() if m else 'No match')
m = [Link](r'\S+@\S+\.\S+', 'mail: abc@[Link]')
print('Find email:', [Link]() if m else 'No match')

Output:

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
Enter the string to test : Kunal scored 95 marks
Enter the regex pattern : \d+
MATCH FOUND : "95" at position 15

--- Preset Pattern Demos ---


Find digits: 9876543210
Find a word: Hello
Starts with caps : R
Find email: abc@[Link]

Page 9
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 7 : Aggregation Functions on a Dataset

Objective:
Create a sample dataset and apply: mean(), median(), min(), max(), std(), var(), and sum() aggregation functions.

Theory:
Pandas and NumPy provide vectorized aggregation functions on Series and DataFrames: mean() — arithmetic average; median() — middle value;
std() — standard deviation; var() — variance; sum() — total of all values.

Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import pandas as pd
data = {
'Student': ['Kunal', 'Aryan', 'Abhinav', 'Aditya', 'Aishwarya', 'Sachin'],
'Math': [85, 78, 92, 88, 70, 95],
'Science': [90, 82, 76, 95, 84, 88],
'English': [75, 88, 84, 79, 91, 72],
'DSA': [92, 70, 88, 85, 78, 96],
}
df = [Link](data)
print('Student Marks Dataset:')
print(df.to_string(index=False))
nums = df[['Math', 'Science', 'English', 'DSA']]
print('\n--- Aggregation Results ---')
print('Mean(average):\n', [Link]().round(2))
print('\nMedian (middle val) :\n', [Link]())
print('\nMin(smallest):\n', [Link]())
print('Max(largest):\n', [Link]())
print('\nStd Dev (spread):\n', [Link]().round(2))
print('\nVariance:\n', [Link]().round(2))
print('\nSum(total):\n', [Link]())

Output:

Page 10
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Name
Name :
: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :
: 0905CD241045
0905CD241020
----------------------------------------
Student Marks Dataset:
Student Math Science English DSA
Kunal 85 90 75 92
Aryan 78 82 88 70
Abhinav 92 76 84 88
Aditya 88 95 79 85
Aishwarya 70 84 91 78
Sachin 95 88 72 96

--- Aggregation Results ---


Mean(average):
Math 84.67
Science 85.83
English 81.50
DSA 84.83
dtype: float64

Median (middle val) :


Math 86.5
Science 86.0
English 81.5
DSA 86.5
dtype: float64

Min(smallest):
Math 70
Science 76
English 72
DSA 70
dtype: int64
Max(largest):
Math 95
Science 95
English 91
DSA 96
dtype: int64

Std Dev (spread):


Math 9.29
Science 6.65
English 7.45
DSA 9.52
dtype: float64

Variance:
Math 86.27
Science 44.17
English 55.50
DSA 90.57
dtype: float64

Sum(total):
Math 508
Science 515
English 489
DSA 509
dtype: int64

Page 11
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 8 : Row-wise Proportion using [Link]()

Objective:
Write a Python program to get row-wise proportions using Pandas [Link]() function.

Theory:
[Link]() computes a cross-tabulation table of two or more factors. The normalize='index' parameter computes row-wise proportions (each
row sums to 1.0), while normalize='columns' gives column-wise proportions.

Program Code:

print('Name
print('Name :',
:', 'Rishav
'Devraj Sagar')
Shivhare')
print('Roll No
print('Roll No :',
:', '0905CD241045')
'0905CD241020')
print('-' * 40)
import pandas as pd
data = {
'Gender': ['M','F','M','F','M','F','M','F','M','F'],
'Grade': ['A','B','A','A','C','B','B','A','C','B'],
'Branch': ['CSE','CSE','IT','ECE','CSE','IT','ECE','CSE','IT','ECE'],
}
df = [Link](data)
print('Survey Data:')
print(df)
freq = [Link](df['Gender'], df['Grade'])
print('\nFrequency Table (count of each grade per gender):')
print(freq)
row_prop = [Link](df['Gender'], df['Grade'], normalize='index')
print('\nRow-wise Proportion (each row sums to 1.0):')
print(row_prop.round(2))
col_prop = [Link](df['Gender'], df['Grade'], normalize='columns')
print('\nColumn-wise Proportion (each column sums to 1.0):')
print(col_prop.round(2))

Output:

Page 12
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Name
Name :: Rishav
Devraj Sagar
Shivhare
Roll No
Roll No :: 0905CD241045
0905CD241020
----------------------------------------
Survey Data:
Gender Grade Branch
0 M A CSE
1 F B CSE
2 M A IT
3 F A ECE
4 M C CSE
5 F B IT
6 M B ECE
7 F A CSE
8 M C IT
9 F B ECE

Frequency Table (count of each grade per gender):


Grade A B C
Gender
F 2 3 0
M 2 1 2

Row-wise Proportion (each row sums to 1.0):


Grade A B C
Gender
F 0.4 0.6 0.0
M 0.4 0.2 0.4

Column-wise Proportion (each column sums to 1.0):


Grade A B C
Gender
F 0.5 0.75 0.0
M 0.5 0.25 1.0

Page 13
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 9 : Bar Chart — Programming Language Popularity

Objective:
Write a Python program to display a bar chart showing the popularity of various programming languages using Matplotlib.

Theory:
Matplotlib's [Link]() creates vertical bar charts. Labels, colors, and annotations can be customized. The [Link]() displays the chart. Data source:
TIOBE/PYPL-style popularity index.

Program Code:

import matplotlib
[Link]('Agg')
import [Link] as plt

languages = ['Python', 'Java', 'C++', 'JavaScript', 'R', 'Go']


popularity = [30.3, 17.9, 15.6, 12.1, 7.4, 6.1]
colors = ['#2196F3', '#4CAF50', '#FF5722', '#FFC107', '#9C27B0', '#00BCD4']

fig, ax = [Link](figsize=(9, 5))


bars = [Link](languages, popularity, color=colors, edgecolor='black', linewidth=0.7)
ax.set_title('Popularity of Programming Languages (%)', fontsize=14, fontweight='bold')
ax.set_xlabel('Programming Language', fontsize=12)
ax.set_ylabel('Popularity (%)', fontsize=12)
ax.set_ylim(0, 36)
[Link](axis='y', linestyle='--', alpha=0.5)
for bar, val in zip(bars, popularity):
[Link](bar.get_x() + bar.get_width()/2, bar.get_height()+0.3, f'{val}%',
ha='center', fontsize=10, fontweight='bold')
plt.tight_layout()
[Link]('/home/claude/work/lang_popularity.png', dpi=150)

Output:

Page 14
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Page 15
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Experiment 10 : Grouped Bar Chart — Scores by Subject and Gender

Objective:
Create a grouped bar chart displaying scores by subject for men and women using multiple X values on the same chart.

Theory:
Grouped bar charts use [Link]() for base X positions and shift each group by width/2 to avoid overlap. This allows multiple bars per X-
category — one per group. Each call to [Link]() draws one set of bars.

Program Code:

import matplotlib
[Link]('Agg')
import [Link] as plt
import numpy as np

subjects = ['Math', 'Science', 'English', 'History', 'Art']


men_scores = [72, 85, 68, 79, 65]
women_scores = [80, 78, 88, 74, 90]
x = [Link](len(subjects))
width = 0.35

fig, ax = [Link](figsize=(10, 5))


bars_men = [Link](x - width/2, men_scores, width, label='Men', color='#1976D2', edgecolor='black', linewidth=0.7)
bars_women = [Link](x + width/2, women_scores, width, label='Women', color='#E91E63', edgecolor='black', linewidth=0.7)
ax.set_title('Scores by Subject and Gender', fontsize=14, fontweight='bold')
ax.set_xlabel('Subject', fontsize=12)
ax.set_ylabel('Score', fontsize=12)
ax.set_xticks(x)
ax.set_xticklabels(subjects)
[Link](fontsize=11)
ax.set_ylim(0, 105)
[Link](axis='y', linestyle='--', alpha=0.4)
for bars in [bars_men, bars_women]:
for bar in bars:
[Link](bar.get_x()+bar.get_width()/2, bar.get_height()+1, str(int(bar.get_height())),
ha='center', va='bottom', fontsize=9, fontweight='bold')
plt.tight_layout()
[Link]('/home/claude/work/grouped_bar.png', dpi=150)

Output:

Page 16
CSE – DATA SCIENCE / Jan – June 2026 / CD 406 - Practical File

Page 17

You might also like