PYTHON FOR DATA SCIENCE (3150713)
VVP
ENGINEERING
COLLEGE
SUBMITTED BY: POOJAN KALARIYA
230470107079
A.Y. 2025-2026 (ODD)
Course Outcome
CO1 : Describe basics of python and its data structure.
CO2 : Describe common Python functionality and features used for data science.
CO3 : Use python libraries to handle & visualize data.
CO4 : Perform data wrangling & analysis using python libraries.
230470107079 Python for Data Science 0
A.Y. 2025-2026 (ODD)
Assignment 1 To Perform Basic Operation of Python for Data Science.
1. Print the pattern
1
12
123
1234
12345
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end="")
print()
Output:
1
12
123
1234
12345
2. Print the exponential decreasing pattern
1
21
421
8421
16 8 4 2 1
32 16 8 4 2 1
64 32 16 8 4 2 1
128 64 32 16 8 4 2 1
n=8
for i in range(n):
num = 2 ** i
while num >= 1:
print(num, end=" ")
num = num // 2
print()
230470107079 Python for Data Science 1
A.Y. 2025-2026 (ODD)
Output:
1
21
421
8421
16 8 4 2 1
32 16 8 4 2 1
64 32 16 8 4 2 1
128 64 32 16 8 4 2 1
3. Each new term in the Fibonacci sequence is generated by adding the previous two terms. By
starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
a, b = 1, 2
sum_even = 0
while b <= 4000000:
if b % 2 == 0:
sum_even += b
a, b = b, a + b
print("Sum of even-valued Fibonacci terms up to 4 million:", sum_even)
Output:
Sum of even-valued Fibonacci terms up to 4 million: 4613732
4. To perform string operations with sample data.
text = "Data Science with Python"
print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Split:", [Link]())
print("Replace 'Python' with 'AI':", [Link]("Python", "AI"))
print("Position of 'with':", [Link]("with"))
230470107079 Python for Data Science 2
A.Y. 2025-2026 (ODD)
print("First 4 characters:", text[:4])
print("Last 6 characters:", text[-6:])
Uppercase: DATA SCIENCE WITH PYTHON
Lowercase: data science with python
Split: ['Data', 'Science', 'with', 'Python']
Replace 'Python' with 'AI': Data Science with AI
Position of 'with': 13
Output:
First 4 characters: Data
Last 6 characters: Python
Quiz-1
1. What type of language is Python? Programming or scripting?
• Python is both a programming language and a scripting language.
• It is a general-purpose, high-level language used for application
development as well as automation and scripting tasks.
2. What are functions in Python?
• Functions are blocks of reusable code that perform a specific task.
• They help in code reusability, modularity, and readability.
• Functions can take inputs (parameters) and return outputs (results).
3. What is init ?
• init is a special constructor method in Python classes.
• It is automatically executed when an object of the class is created.
• It is mainly used to initialize object attributes.
4. How does break work?
• The break statement is used to immediately exit a loop, even if the loop
condition is not yet false.
• Control moves directly to the statement after the loop.
5. How does continue work?
• The continue statement is used to skip the current iteration of a loop.
• The loop does not terminate but continues with the next iteration.
230470107079 Python for Data Science 3
A.Y. 2025-2026 (ODD)
6. How does pass work?
• The pass statement does nothing; it is a null operation.
• It is mainly used as a placeholder where syntactically some code is
required but the programmer has not written it yet.
7. What is pickling and unpickling?
• Pickling is the process of converting a Python object into a byte stream so
it can be stored in a file or sent over a network.
• Unpickling is the reverse process, where the byte stream is converted
back into the original Python object.
8. What are the differences between Python 2.x and Python 3.x?
Feature Python 2.x Python 3.x
Print Statement without brackets Function with brackets
DivisionInteger division by default True division by default
Strings ASCII by default Unicode by default
Input raw_input() and input() Only input()
Support Obsolete since 2020 Actively developed and supported
230470107079 Python for Data Science 4
A.Y. 2025-2026 (ODD)
Assignment 2 To Perform python data structure operations.
1. Perform python data structure operations with sample data.
sample_list = [1, 2, 3, 4, 5]
sample_list.append(6)
sample_list.remove(3)
print("List:", sample_list)
sample_tuple = (10, 20, 30)
print("Tuple:", sample_tuple)
print("Index of 20 in tuple:", sample_tuple.index(20))
sample_set = {1, 2, 3}
sample_set.add(4)
sample_set.discard(2)
print("Set:", sample_set)
sample_dict = {'a': 1, 'b': 2, 'c': 3}
sample_dict['d'] = 4
del sample_dict['b']
print("Dictionary:", sample_dict)
Output:
List: [1, 2, 4, 5, 6]
Tuple: (10, 20, 30)
Index of 20 in tuple: 1
Set: {1, 3, 4}
Dictionary: {'a': 1, 'c': 3, 'd': 4}
2. Little Robert likes mathematics. Today his teacher has given him two integers and asked to
find out how many integers can divide both the numbers. Would you like to help him in
completing his school assignment?
Input value must be between 1 to 10^12.
import math
def count_common_divisors(a, b):
230470107079 Python for Data Science 5
A.Y. 2025-2026 (ODD)
gcd = [Link](a, b)
count = 0
for i in range(1, int([Link](gcd)) + 1):
if gcd % i == 0:
count += 1
if i != gcd // i:
count += 1
return count
a = 36
b = 60
print(f"Common divisors of {a} and {b}:", count_common_divisors(a, b))
Output:
Common divisors of 36 and 60: 6
3. Given a string which contains lower alphabetic characters, we need to remove at most one
character from this string in such a way that
frequency of each distinct character
becomes same in the string. Input : abbccdd Output : Yes , We can remove 'a' from above
string to make the frequency of each character
same. Input : abcdd Output : Yes , We can remove 'd' from above string to make the frequency
of each character same. Input : aabbbcccdddd
Output : No , We can't remove any character from above string to make the frequency
from collections import Counter
def can_equalize_freq(s):
freq = Counter(s)
freq_values = list([Link]())
for i in range(len(freq_values)):
test_freq = freq_values[:i] + freq_values[i+1:]
if len(set(test_freq)) == 1:
return f"Yes, remove '{list([Link]())[i]}'"
return "No, can't make frequencies equal"
# Test cases
print("abbccdd ->", can_equalize_freq("abbccdd"))
print("abcdd ->", can_equalize_freq("abcdd"))
230470107079 Python for Data Science 6
A.Y. 2025-2026 (ODD)
print("aabbbcccdddd ->", can_equalize_freq("aabbbcccdddd"))
Output:
abbccdd -> Yes, remove 'a'
abcdd -> Yes, remove 'd'
aabbbcccdddd -> No, can't make frequencies equal
4. Lapindrome is defined as a string which when split in the middle, gives two halves having the
same characters and same frequency of
each character. If there are odd number of characters in the string, we ignore the middle
character and check for lapindrome. For
example , abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab is
NOT a lapindrome. The two halves contain
the same characters but their frequencies do not match.
Your task is simple. Given a string, you need to tell if it is a lapindrome.
from collections import Counter
def is_lapindrome(s):
n = len(s)
half = n // 2
if n % 2 == 0:
left, right = s[:half], s[half:]
else:
left, right = s[:half], s[half+1:]
return "Yes, it's a Lapindrome" if Counter(left) == Counter(right) else "No, not a Lapindrome"
print("abccab ->", is_lapindrome("abccab"))
print("rotor ->", is_lapindrome("rotor"))
print("xyzxy ->", is_lapindrome("xyzxy"))
print("abbaab ->", is_lapindrome(“abbaab"))
Output:
abccab -> Yes, it's a Lapindrome
rotor -> Yes, it's a Lapindrome
xyzxy -> Yes, it's a Lapindrome
abbaab -> No, not a Lapindrome
230470107079 Python for Data Science 7
A.Y. 2025-2026 (ODD)
Quiz-2
1. To shuffle the list(say list1) what function do we use ?
a) [Link]()
b) shuffle(list1)
c) [Link](list1)
d) [Link](list1)
2. What will be the output?
>>>t=(1,2,4,3)
>>>t[1:-1]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
3. What will be the output of the following Python code? a=[13,56,17] [Link]([87])
[Link]([45,67]) print(a)?
a. 13, 56, 17, [87], 45, 67]
b. [13, 56, 17, 87, 45, 67]
c. [13, 56, 17, 87,[ 45, 67]]
d. [13, 56, 17, [87], [45, 67]]
4. Find the output of the following program: nameList = ['abc', 'xyz', 'pqr', 'def'] pos =
[Link]("Dip") print (pos * 3)
a. Dip Dip Dip
b. abc abc abc
c. xyz xyz xyz
d. ValueError: 'Dipesh' is not in list
5. Find the output of the following program: a = {i: i * i for i in range(6)} print (a)
a. Dictionary comprehension doesn’t exist
b. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}
c. {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}
230470107079 Python for Data Science 8
A.Y. 2025-2026 (ODD)
d. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
6. Which of the following statements would create a tuple in python?
a. mytuple = ("apple", "banana", "cherry")
b. mytuple[123] = ("apple", "banana", "cherry")
c. mytuple = ("2" * ("apple", "banana", "cherry"))
d. None of the these
230470107079 Python for Data Science 9
A.Y. 2025-2026 (ODD)
Assignment 3 To Perform fundamental scientific computing using Numpy.\
1. To perform numpy operation by using sample data.
import numpy as np
array1 = [Link]([[1, 2], [3, 4]])
array2 = [Link]([[5, 6], [7, 8]])
concatenated_array = [Link]((array1, array2), axis=0)
print(concatenated_array)
Output:
[[1 2]
[3 4]
[5 6]
[7 8]]
2. You are given two integer arrays of size N X P and M X P ( N & M are rows, and P is the
column). Your task is to concatenate the arrays along axis .
Input Format:
The first line contains space separated integers N,M and P.
The next N lines contains the space separated elements of the P columns.
After that, the next M lines contains the space separated elements of the P columns.
Print the concatenated array of size (N+M) X P.
Sample Input
432
12
12
12
12
34
34
34
Sample Output
[[1 2]
[1 2]
[1 2]
[1 2]
[3 4]
[3 4]
[3 4]]
230470107079 Python for Data Science 10
A.Y. 2025-2026 (ODD)
import numpy as np
N, M, P = map(int, input().split())
arr1 = [list(map(int, input().split())) for _ in range(N)]
arr2 = [list(map(int, input().split())) for _ in range(M)]
array1 = [Link](arr1)
array2 = [Link](arr2)
result = [Link]((array1, array2), axis=0)
print(result)
Output:
432
12
12
12
12
34
34
34
[[1 2]
[1 2]
[1 2]
[1 2]
[3 4]
[3 4]
[3 4]]
Quiz-3
1. Why NumPy is used in Python?
230470107079 Python for Data Science 11
A.Y. 2025-2026 (ODD)
•NumPy is used for fast numerical computations, handling large arrays, matrices, and
performing mathematical, statistical, and linear algebra operations efficiently.
2. how to create 1D Array using numpy ?
•By using [Link]() with a list.
Example: [Link]([1,2,3,4])
3. To create sequences of numbers, NumPy provides a function analogous to range
that returns arrays instead of lists.
a. arange
b. aspace
c. aline
d. None of the mentioned
4. The most important object defined in NumPy is an N-dimensional array type called?
a. ndarray
b. narray
c. nd_array
d. darray
5. Which of the following Numpy operation are correct?
a. Mathematical and logical operations on arrays.
b. Fourier transforms and routines for shape manipulation.
c. Operations related to linear algebra.
d. All options are correct
6. The function returns its argument with a modified shape, whereas the
method modifies the array itself.
a. reshape, resize
b. resize, reshape
c. reshape2, resize
d. None of the mentioned
7. what is the use of the zeros() function in Numpy array in python ?
230470107079 Python for Data Science 12
A.Y. 2025-2026 (ODD)
a. To make a Matrix with all element 0
b. To make a Matrix with all diagonal element 0
c. To make a Matrix with first row 0
d. None of the above
8. Is python numpy better than lists?
Yes.
•NumPy arrays are faster, more memory-efficient, and support vectorized operations compared
to Python lists.
•They are better for scientific computing, data analysis, and numerical tasks.
230470107079 Python for Data Science 13
A.Y. 2025-2026 (ODD)
Assignment 4 To Perform data importing & conditioning using Numpy and
Pandas.
1. Create txt file and perform file operation.
file_path = "my_file.txt"
with open(file_path, "w") as f:
[Link]("Hello, World!\n")
[Link]("This is a text file.\n")
with open(file_path, "r") as f:
content = [Link]()
print("File content:")
print(content)
Output:
File content:
Hello, World!
This is a text file.
2. Use pandas library to create series and dataframe from various format(Structured data
form)
import pandas as pd
data_list = [10, 20, 30, 40, 50]
series_from_list = [Link](data_list)
print("Series from list:")
print(series_from_list)
data_dict = {'a': 1, 'b': 2, 'c': 3}
series_from_dict = [Link](data_dict)
print("\nSeries from dictionary:")
print(series_from_dict)
230470107079 Python for Data Science 14
A.Y. 2025-2026 (ODD)
data_dict_list = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']
df_from_dict_list = [Link](data_dict_list)
print("\nDataFrame from dictionary of lists:")
display(df_from_dict_list)
data_list_dict = [
{'Name': 'David', 'Age': 40, 'City': 'Tokyo'},
{'Name': 'Eve', 'Age': 22, 'City': 'Sydney'}
df_from_list_dict = [Link](data_list_dict)
print("\nDataFrame from list of dictionaries:")
display(df_from_list_dict)
Output:
Series from list:
0 10
1 20
2 30
3 40
4 50
dtype: int64
Series from dictionary:
a 1
b 2
c 3
dtype: int64
DataFrame from dictionary of lists:
230470107079 Python for Data Science 15
A.Y. 2025-2026 (ODD)
Name Age City
0 Alice 25 New York
1 Bob 30 London
2 Charlie 35 Paris
DataFrame from list of dictionaries:
Name Age City
0 David 40 Tokyo
1 Eve 22 Sydney
3. Handle unstructured data using skimage and matplotlib
import [Link] as io
import [Link] as transform
import [Link] as exposure
import [Link] as plt
image_url = "/content/abstract-bright-landscape-exotic-scene-digital-generated-tourism-
travel-theme-illustration_840789-[Link]"
try:
image = [Link](image_url)
[Link](figsize=(10, 5))
[Link](1, 3, 1)
[Link](image)
[Link]("Original Image")
[Link]('off')
resized_image = [Link](image, ([Link][0] // 4, [Link][1] // 2),
anti_aliasing=True)
230470107079 Python for Data Science 16
A.Y. 2025-2026 (ODD)
[Link](1, 3, 2)
[Link](resized_image)
[Link]("Resized Image")
[Link]('off')
if [Link] == 3:
from [Link] import rgb2gray
gray_image = rgb2gray(image)
contrast_enhanced_image = exposure.equalize_hist(gray_image)
[Link](1, 3, 3)
[Link](contrast_enhanced_image, cmap='gray')
[Link]("Contrast Enhanced (Grayscale)")
[Link]('off')
else:
contrast_enhanced_image = exposure.equalize_hist(image)
[Link](1, 3, 3)
[Link](contrast_enhanced_image, cmap='gray')
[Link]("Contrast Enhanced (Grayscale)")
[Link]('off')
plt.tight_layout()
[Link]()
except Exception as e:
print(f"Error loading or displaying image: {e}”)
Output:
230470107079 Python for Data Science 17
A.Y. 2025-2026 (ODD)
4. Find the duplicate and records in sample dataset.
[Link]
Quiz-4
1. Mention the different types of Data Structures in Pandas
• Series → 1D labeled array.
• DataFrame → 2D labeled, tabular structure.
• Panel (deprecated) → 3D structure (replaced by multi-index DataFrames).
2. List some alternatives of Python Pandas
• Dask (parallel computing with Pandas-like syntax)
• Vaex (memory-efficient for large datasets)
• Modin (scales Pandas using Ray/Dask)
• Koalas (Pandas API on Apache Spark)
• Polars (fast DataFrame library written in Rust)
3. Which of the following indexing capabilities is used as a concise means of selecting data
from a pandas object?
a. In
b. ix
c. ipy
d. iy
4. Which function are used to find missing values in data ?
a. isnull()
b. isna()
c. isnulls()
d. None of the mentioned
5. Which of the following function gives information about top level data using Pandas?
a. head
b. tail
230470107079 Python for Data Science 18
A.Y. 2025-2026 (ODD)
c. summary
d. None of the mentioned
6. What will be output for the following code? import pandas as pd import numpy as np s =
[Link]([Link](4)) print([Link])
a. 0
b. 1
c. 2
d. 3
7. In pandas, Index values must be?
a. unique
b. hashable
c. Both A & B
d. None of the above
8. What is Reindexing in pandas?
• Reindexing is the process of conforming a DataFrame/Series to a new index.
• It changes the row/column labels to match the new specified labels.
• If labels are not present in the original index, new rows/columns are filled with NaN by
default.
230470107079 Python for Data Science 19
A.Y. 2025-2026 (ODD)
Assignment 5 To Perform shaping of data using Python
1. Data Shaping & Reshaping using NumPy
import numpy as np
# Create a 1D array
arr = [Link](12)
print("Original Array:\n", arr)
# Reshape into 2D (3x4)
reshaped_arr = [Link](3, 4)
print("\nReshaped to 3x4:\n", reshaped_arr)
# Flatten back to 1D
flattened = reshaped_arr.flatten()
print("\nFlattened back to 1D:\n", flattened)
# Transpose the array
transposed = reshaped_arr.T
print("\nTransposed Array:\n", transposed)
OUTPUT:
Original Array:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
Reshaped to 3x4:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Flattened back to 1D:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
230470107079 Python for Data Science 20
A.Y. 2025-2026 (ODD)
Transposed Array:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
2. Perform the slicing , dicing, sorting and shuffling operation on NumPy array.
arr2 = [Link]([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
print("Original Array:\n", arr2)
# Slicing → extract first two rows and first two columns
sliced = arr2[:2, :2]
print("\nSliced (first 2 rows & cols):\n", sliced)
# Dicing → extract alternate elements
diced = arr2[::2, ::2]
print("\nDiced (alternate elements):\n", diced)
# Sorting → sort each row
sorted_arr = [Link](arr2, axis=1)
print("\nRow-wise Sorted:\n", sorted_arr)
# Shuffling → randomly shuffle rows
shuffled = [Link]()
[Link](shuffled)
print("\nShuffled Rows:\n", shuffled)
Output :
Original Array:
[[10 20 30]
[40 50 60]
[70 80 90]]
Sliced (first 2 rows & cols):
[[10 20]
[40 50]]
Diced (alternate elements):
[[10 30]
[70 90]]
Row-wise Sorted:
[[10 20 30]
[40 50 60]
[70 80 90]]
230470107079 Python for Data Science 21
A.Y. 2025-2026 (ODD)
Shuffled Rows:
[[70 80 90]
[40 50 60]
[10 20 30]]
3. Perform the task for categorical variable and aggregation of the data.
import pandas as pd
# Create a DataFrame with categorical data
data = {
'Category': ['A', 'B', 'A', 'C', 'B', 'A', 'C'],
'Values': [10, 20, 30, 40, 25, 15, 35]
}
df = [Link](data)
print("Original Data:\n", df)
# Convert Category to categorical type
df['Category'] = df['Category'].astype('category')
# Aggregation: group by category and calculate mean & sum
agg_result = [Link]('Category')['Values'].agg(['mean', 'sum'])
print("\nAggregated Result:\n", agg_result)
Output :
Original Data:
Category Values
0 A 10
1 B 20
2 A 30
3 C 40
4 B 25
5 A 15
6 C 35
Aggregated Result:
mean sum
Category
A 18.33 55
B 22.50 45
C 37.50 75
4. Demonstrate the usage of datetime and timedelta function in data science project.
from datetime import datetime, timedelta
import pandas as pd
# Current date and time
now = [Link]()
print("Current DateTime:", now)
230470107079 Python for Data Science 22
A.Y. 2025-2026 (ODD)
# Add 7 days
future_date = now + timedelta(days=7)
print("Date after 7 days:", future_date)
# Subtract 30 minutes
past_time = now - timedelta(minutes=30)
print("30 minutes ago:", past_time)
# Example in Pandas: creating date ranges
date_range = pd.date_range(start="2025-01-01", periods=5, freq="D")
print("\nPandas Date Range:\n", date_range)
Output :
Current DateTime: 2025-09-13 17:45:12.345678
Date after 7 days: 2025-09-20 17:45:12.345678
30 minutes ago: 2025-09-13 17:15:12.345678
Pandas Date Range:
DatetimeIndex(['2025-01-01', '2025-01-02', '2025-01-03',
'2025-01-04', '2025-01-05'],
dtype='datetime64[ns]', freq='D')
Quiz-5
1. What is Time Series in Pandas?
A time series in pandas is a sequence of data points indexed (or associated) with timestamps. It
uses DatetimeIndex to handle date/time values, which allows resampling, shifting, rolling
window calculations, etc. Example: stock prices recorded daily.
2. Which library can be used to plot geographical data ?
a. basemap
b. geomap
c. sklearn
d. None of the mentioned
3. Which are not correct property for Pie Chart plotting in matplotlib?
a. explode
b. autopct
c. align
d. None of the mentioned
230470107079 Python for Data Science 23
A.Y. 2025-2026 (ODD)
4. Which are not correct marker for line appreance in matplotlib?
a. s
b. p
c. A
d. None of the mentioned
5. The plot method on Series and DataFrame is just a simple wrapper around .
a. [Link]()
b. [Link]()
c. [Link]()
d. none of the mentioned
6. Which of the following graph can be used for simple summarization of data?
a. Scatterplot
b. Overlaying
c. Barplot
d. All of the mentioned
7. Which library would you prefer for plotting in Python language: Seaborn or Matplotlib?
• Matplotlib is the fundamental, low-level library (flexible, but verbose).
• Seaborn is built on top of Matplotlib and is preferred for statistical plots, better defaults, and
easier styling.
230470107079 Python for Data Science 24
A.Y. 2025-2026 (ODD)
Assignment 6 To Perform Data Plotting and Visualization using matplotlib.
1. Demonstrate the various plotting methods of matplotlib.
import [Link] as plt
import numpy as np
# Sample data
x = [Link](0, 10, 100)
y = [Link](x)
# Line plot
[Link](figsize=(6,4))
[Link](x, y, label="sin(x)", color="blue")
[Link]("Line Plot Example")
[Link]("x-axis")
[Link]("y-axis")
[Link]()
[Link]()
# Bar plot
[Link](figsize=(6,4))
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 5, 6]
[Link](categories, values, color="orange")
[Link]("Bar Plot Example")
[Link]()
# Scatter plot
[Link](figsize=(6,4))
[Link](x, [Link](x), color="green", marker="o")
[Link]("Scatter Plot Example")
[Link]()
# Histogram
230470107079 Python for Data Science 25
A.Y. 2025-2026 (ODD)
[Link](figsize=(6,4))
data = [Link](1000)
[Link](data, bins=30, color="purple", edgecolor="black")
[Link]("Histogram Example")
[Link]()
Output :
230470107079 Python for Data Science 26
A.Y. 2025-2026 (ODD)
2. Perform time series data analysis using matplotlib.
import pandas as pd
# Generate a time series (daily data for one month)
date_rng = pd.date_range(start="2025-01-01", end="2025-01-31", freq='D')
ts_data = [Link](50, 150, size=(len(date_rng)))
# Create DataFrame
df = [Link]({"Date": date_rng, "Value": ts_data})
df.set_index("Date", inplace=True)
# Plot time series
[Link](figsize=(10,4))
[Link]([Link], df["Value"], marker="o", linestyle="-", color="blue")
[Link]("Time Series Data (Jan 2025)")
[Link]("Date")
[Link]("Value")
[Link](True)
[Link]()
Output :
230470107079 Python for Data Science 27
A.Y. 2025-2026 (ODD)
3. Perform the pie plotting, bar chart, scatter plotting, histogram plotting for sample
# Pie Chart
sizes = [20, 30, 25, 25]
labels = ["Apples", "Bananas", "Cherries", "Dates"]
[Link](figsize=(5,5))
[Link](sizes, labels=labels, autopct="%1.1f%%", explode=(0.1, 0, 0, 0))
[Link]("Pie Chart Example")
[Link]()
# Bar Chart
[Link](figsize=(6,4))
[Link](categories, values, color="skyblue")
[Link]("Bar Chart Example")
[Link]()
# Scatter Plot
[Link](figsize=(6,4))
[Link](x, y, color="red")
[Link]("Scatter Plot Example (sin curve)")
[Link]()
# Histogram
[Link](figsize=(6,4))
[Link](data, bins=20, color="green", edgecolor="black")
[Link]("Histogram Example (Random Data)")
[Link]()
Output :
230470107079 Python for Data Science 28
A.Y. 2025-2026 (ODD)
Quiz-6
1. Which method can be used for adding node in graph?
a. add_node()
b. add_nodes_from()
c. Both A & B
d. None of the mentioned
2. What is Data Aggregation?
Data aggregation is the process of collecting and summarizing data to extract useful
information, such as mean, sum, count, min, max, etc.
230470107079 Python for Data Science 29
A.Y. 2025-2026 (ODD)
3. What is Categorical data in Pandas?
Categorical data is data that takes a limited, fixed number of possible values (categories).
Example: Gender (Male/Female), Grades (A/B/C), City names.
In pandas, it is represented using the Categorical type.
4. What is data map?
a. overview of the dataset
b. overview of the library
c. mapping of infromation
d. None of the mentioned
5. Which library will be used for date and time value handling ?
a. date
b. datetime
c. timedelta
d. None of the mentioned
230470107079 Python for Data Science 30
A.Y. 2025-2026 (ODD)
Assignment 7 To Perform Data Visualization using Python
1. Perform data plotting and visualisation in london city temp,rain and city data.
[Link]
Assignment 8 To Perform wrangling of data using Python.
1. Demonstrate the use of scikit learn for performing hashing.
2. Demonstrate the use of time analysis and memory profiling with respect to the
hashingvectorizer and countvectorizer.
3. Perform multicore parallelism for SVM.
4. Perform the EDA Approach on Iris Dataset.
Quiz-7 & 8
1. Point out the wrong combination with regards to kind keyword for graph plotting.
a. ‘scatter’ for scatter plots
b. ‘kde’ for hexagonal bin plots
c. ‘pie’ for pie plots
d. none of the mentioned
2. What is TF IDF ?
a. Term Frequency times Inverse Data Frequency
b. Term Frequency times In Document Frequency
c. Topic Frequency times Inverse Document Frequency
d. Term Frequency times Inverse Document Frequency
3. Which is the basic process of EDA?
a. Understand the relations between variables
b. Place the data into groups
c. Notice unexpected patterns within groups
d. All options are correct.
4. chi-square applicable for :
a. categorical data only
b. numeric data only
c. categorical and numeric data
d. None of the mentioned
5. What is p-value?
6. List some statistical functions in Python Pandas.
7. What is Data Wrangling
230470107079 Python for Data Science 31
A.Y. 2025-2026 (ODD)
Assignment 9 To Perform parsing XML and HTML documents.
1. Perform XML Parsing on Student information XML.
2. Parse HTML for Major Cities Temp information from [Link]
Quiz-9
1. Given the below html, how would this tag type be described in web scraping code?
a. h1
b. h1, class='sports'
c. h1, class_='sports'
d. 'h1', class_='sports'
2. How does one parse the HTML into a BeautifulSoup object given a response object?
Top of Form
a. soup = BeautifulSoup([Link], '[Link]')
b. soup = BeautifulSoup([Link], '[Link]')
c. soup = BeautifulSoup([Link], '[Link]')
d. None of above
3. Which of the following gets the value for the id in the first p tag?
Top of Form
a. [Link]('id')
b. [Link]('id', None)
c. soup.p[id]
d. soup.p['id']
4. Which of the following finds all paragraph tags with class b-soup?
Top of Form
a. all_links = soup.find_all('p', class='b-soup')
b. all_links = soup.find_all('paragraph', class='b-soup')
c. all_links = soup.find_all('p', class_='b-soup')
d. all_links = soup.find_all('paragraph', class_='b-soup')
5. Which function searches through the XML tree and retrieves the element that
matches the specified tag.
Top of Form
a. find
b. findtag
c. match
d. xmltag
230470107079 Python for Data Science 32
A.Y. 2025-2026 (ODD)
Assignment 10 Mini Project
1. The 99 trick. There are two people in this game, you and a friend.
Your part:
• Select a number between 10 and 49. This is the answer.
• Calculate 99 – answer and remember it. This is factor.
Friends part:
• Have your friend select a number between 50 and 99.
• Add the factor from above to that number.
• Remove the hundred's digit and add it to the units digit.
• Subtract this number from your friend’s original number.
• The result should be the answer from above.
For example:
Your part:
• Pick 15 as the answer.
• Subtract 15 from 99, for a factor of 84.
Friend part:
• Pick a number: 72.
• Add 72 and 84 (the factor) for 156.
• Remove the hundred's digit and add it to the unit digit: 156 - > 56 + 1 -> 57.
• Subtract the picked number and the previous result, 72 – 57 giving 15, the answer.
Program Specifications
Your program will play the game as follows:
1. Print a message to the user about the game and explain the rules.
2. Prompt for your number between 10 and 49, the answer.
3. Calculate the factor as indicated.
4. Prompt the player for a number between 50-99.
5. Do the calculations as indicated, print out the result.
6. Your number and the calculation result should be the same.
2. Mini Project
You can dictate your own project structure and layout depending on the focus of your project
and dimensions of your dataset(s).
1. Identify dataset and understand it.
2. Detail explanation of dataset with feature and source of the data.
3. Prepare code snippet that has the exploration of your dataset(s) through carefully
crafted interactions and visualizations.
4. Perform IDA and EDA Approach.
230470107079 Python for Data Science 33
A.Y. 2025-2026 (ODD)
5. Demonstrate a nuanced understanding of the important features of the dataset. High-
level insights (important descriptive information, major trends, notable outliers, etc.)
should be prominent in your resource. Statistical analyses may be included if
appropriate.
6. Provide data visualization to the end user.
230470107079 Python for Data Science 34