0% found this document useful (0 votes)
2 views34 pages

Python Lab Assignment - Google Docs 1

The document outlines a Python for Data Science course, detailing course outcomes and assignments related to basic Python operations, data structures, and string manipulations. It includes code examples for generating patterns, performing mathematical operations, and handling data structures like lists, tuples, sets, and dictionaries. Additionally, it features quizzes on Python concepts such as functions, constructors, and differences between Python versions.

Uploaded by

fedago7767
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)
2 views34 pages

Python Lab Assignment - Google Docs 1

The document outlines a Python for Data Science course, detailing course outcomes and assignments related to basic Python operations, data structures, and string manipulations. It includes code examples for generating patterns, performing mathematical operations, and handling data structures like lists, tuples, sets, and dictionaries. Additionally, it features quizzes on Python concepts such as functions, constructors, and differences between Python versions.

Uploaded by

fedago7767
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

​P​Y​ THON​ ​FOR​ ​DATA​ ​SCIENCE​ ​(3150713)​

​VVP​
​E​N
​ GINEERING​
​C​​OLLEGE​

​S​​UBMITTED​ ​BY​​: H​​ARSH​ ​G​​AJRA​


​230470107061​
​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.​
​A.Y. 2025-2026 (ODD)​

​Assignment 1​​To Perform Basic Operation of Python for Data Science.​


​1. Print the following pattern using python basics.​

​​
1
​12​
​123​
​1234​
​12345​

​Code:​

​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 following pattern using python basics.​

​​
1
​2 1​
​4 2 1​
​8 4 2 1​
​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​

​Code:​

​n = 8​
​for i in range(n):​
​num = 2 ** i​
​while num >= 1:​
​print(num,end=" ")​

​230470107061​ ​Python for Data Science​ ​1​


​A.Y. 2025-2026 (ODD)​

​num = num / 2​
​print()​

​Output:​
​1​
​2 1.0​
​4 2.0 1.0​
​8 4.0 2.0 1.0​
​16 8.0 4.0 2.0 1.0​
​32 16.0 8.0 4.0 2.0 1.0​
​64 32.0 16.0 8.0 4.0 2.0 1.0​
​128 64.0 32.0 16.0 8.0 4.0 2.0 1.0​

​ . Each new term in the Fibonacci sequence is generated by adding the previous two​
3
​terms. By starting with 1 and 2, the first 10 terms will be:​

​1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...​

​ y considering the terms in the Fibonacci sequence whose values do not exceed four​
B
​million, find the sum of the even-valued terms.​

​Code:​

​a, b = 1, 2​
​total = 0​
​while a <= 4000000:​
​if a % 2 == 0:​
​total += a​
​a, b = b, a + b​
​print("Sum of even Fibonacci numbers under 4 million is:", total)​

​Output:​
​Sum of even Fibonacci numbers under 4 million is: 4613732​

​230470107061​ ​Python for Data Science​ ​2​


​A.Y. 2025-2026 (ODD)​

​4. To perform string operations with sample data.​

​Code:​

​# Sample string​
​text = "Python Programming"​
​# 1. Length of string​
​print("Length:", len(text))​
​# 2. Convert to uppercase​
​print("Uppercase:", [Link]())​
​# 3. Convert to lowercase​
​print("Lowercase:", [Link]())​
​# 4. Replace a word​
​print("Replace 'Python' with 'Java':", [Link]("Python", "Java"))​
​# 5. Check if string starts with a word​
​print("Starts with 'Python'?", [Link]("Python"))​
​# 6. Check if string ends with a word​
​print("Ends with 'ing'?", [Link]("ing"))​
​# 7. Split the string​
​print("Split words:", [Link]())​
​# 8. Reverse the string​
​print("Reversed:", text[::-1])​

​Output:​
​Length: 18​
​Uppercase: PYTHON PROGRAMMING​
​Lowercase: python programming​
​Replace 'Python' with 'Java': Java Programming​
​Starts with 'Python'? True​
​Ends with 'ing'? True​
​Split words: ['Python', 'Programming']​
​Reversed: gnimmargorP nohtyP​

​230470107061​ ​Python for Data Science​ ​3​


​A.Y. 2025-2026 (ODD)​

​Quiz-1​
​1​. What type of language is python? Programming or​​scripting?​

​Python is a general-purpose programming language that can be used for both scripting​
​and larger application development. It is often used as a scripting language for​
​automating tasks, but it is also powerful enough to build full-scale applications.​

​2. What are functions in Python?​

​Functions in Python are blocks of reusable code that perform a specific task. They are​
​defined using the def keyword. Example:​
​def greet(name):​
​print("Hello", name)​

​3. What is __init__?​

​__ init __ is a constructor method in Python classes. It is automatically called when an​
​object is created and is used to initialize instance variables.​
​class Person:​
​def __init__(self, name):​
​[Link] = name​

​4. How does break work?​

​break is used to exit a loop prematurely when a certain condition is met.​


​for i in range(5):​
​if i == 3:​
​break​
​print(i)​

​Output:​
​0​
​1​
​2​

​230470107061​ ​Python for Data Science​ ​4​


​A.Y. 2025-2026 (ODD)​

​5. How does continue work?​

​continue skips the current iteration of a loop and jumps to the next one.​
​for i in range(5):​
​if i == 3:​
​continue​
​print(i)​

​Output:​
​0​
​1​
​2​
​4​

​6. How does pass work?​

​pass is a placeholder statement that does nothing. It’s used when a statement is​
​syntactically required but no action is needed.​
​for i in range(5):​
​pass # Will not raise an error even if body is empty​

​7. What is pickling and unpickling?​

​• Pickling: Converting a Python object into a byte stream for storage or transmission.​
​• Unpickling: Reversing the byte stream back into a Python object.​
​Used for saving data using the pickle module.​

​8. What are the differences between Python 2.x and Python 3.x?​

​1.​ ​What is pickling and unpickling?​


​• Pickling: Converting a Python object into a byte stream for storage or​
​transmission.​
​• Unpickling: Reversing the byte stream back into a Python object.​
​Used for saving data using the pickle module.​
​2.​ ​What are the differences between Python 2.x and Python 3.x?​
​3.​ ​Print – In Python 2, print is a statement (print "Hello"), while in Python 3, it is a​
​function (print("Hello")).​
​2)Division – Python 2 performs integer division by default when dividing integers​
​(5/2 gives 2), while Python 3 performs true division (5/2 gives 2.5).​

​230470107061​ ​Python for Data Science​ ​5​


​A.Y. 2025-2026 (ODD)​

​4.​ ​Unicode – In Python 2, strings are ASCII by default and need a u prefix for​
​Unicode (u"Hello"), while in Python 3, all strings are Unicode by default.​
​5.​ ​range/xrange – Python 2 has range() (returns a list) and xrange() (returns an​
​iterator). Python 3 removes xrange() and makes range() return an iterator.​
​6.​ ​Input – Python 2 has raw_input() (string) and input() (evaluates expression). Python​
​3 only has input() which always returns a string.​
​7.​ ​Exceptions – In Python 2, exception syntax is except Exception, e:. In Python 3, it is​
​except Exception as e:.​
​8.​ ​Dictionary methods – In Python 2, .keys(), .values(), .items() return lists. In Python 3,​
​they return iterable views for better memory efficiency.​
​9.​ ​Libraries – Many standard libraries have been reorganized or renamed in Python 3​
​(e.g., ConfigParser is now configparser).​

​230470107061​ ​Python for Data Science​ ​6​


​A.Y. 2025-2026 (ODD)​

​Assignment 2​​To Perform python data structure operations.​


​1.​ ​Perform python data structure operations with sample data.​

​ . List​
1
​Code:​
​my_list = [10, 20, 30, 40]​
​my_list.append(50)​
​my_list.remove(20)​
​my_list[1] = 35​
​print("List:", my_list)​
​ utput:​
O
​List: [10, 35, 40, 50]​

​ . Tuple​
2
​Code:​
​my_tuple = (1, 2, 3, 4)​
​print("Tuple Element at index 2:", my_tuple[2])​
​ utput:​
O
​Tuple Element at index 2: 3​

​ . Set​
3
​Code:​
​my_set = {1, 2, 3}​
​my_set.add(4)​
​my_set.discard(2)​
​print("Set:", my_set)​
​Output:​
​Set: {1, 3, 4}​

​ . Dictionary​
4
​Code:​
​my_dict = {'name': 'John', 'age': 25}​
​my_dict['age'] = 26​
​my_dict['city'] = 'New York'​
​del my_dict['name']​
​print("Dictionary:", my_dict)​
​ utput:​
O
​Dictionary: {'age': 26, 'city': 'New York'}​

​230470107061​ ​Python for Data Science​ ​7​


​A.Y. 2025-2026 (ODD)​

​2.​ L​ ittle 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.​

​Code:​

​import math​

​def count_common_divisors(a, b):​


​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 = 12​
​b = 18​
​print("Common divisors:", count_common_divisors(a, b))​
​Output:​
​Common divisors : 4​

​ . Given a string which contains lower alphabetic characters, we need to remove at most​
3
​one character from this string in such a way that frequency of each distinct character​
​becomes same in the string.​

I​nput : 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​
​of each character same.​

​Code:​

​from collections import Counter​


​def can_equalize_frequency(s):​
​freq = Counter(s)​
​freq_values = list([Link]())​

​230470107061​ ​Python for Data Science​ ​8​


​A.Y. 2025-2026 (ODD)​

​freq_counter = Counter(freq_values)​
​if len(freq_counter) == 1:​
​return "Yes"​
​elif len(freq_counter) == 2:​
​keys = list(freq_counter.keys())​
​if freq_counter[min(keys)] == 1 and min(keys) == 1:​
​return "Yes"​
​elif freq_counter[max(keys)] == 1 and max(keys) - min(keys) == 1:​
​return "Yes"​
​return "No"​
​print(can_equalize_frequency("abbccdd"))​
​print(can_equalize_frequency("abcdd"))​
​print(can_equalize_frequency("aabbbcccdddd"))​
​Output:​

​Yes​
​Yes​
​No​

​ . Lapindrome is defined as a string which when split in the middle, gives two halves having​
4
​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.​

​ ote that abbaab is NOT a lapindrome. The two halves contain the same characters​
N
​but their frequencies do not match.​

​Your task is simple. Given a string, you need to tell if it is a lapindrome.​

​Code:​

​from collections import Counter​


​def is_lapindrome(s):​
​n = len(s)​
​mid = n // 2​
​if n % 2 == 0:​
​left = s[:mid]​
​right = s[mid:]​
​else:​
​left = s[:mid]​
​right = s[mid+1:]​
​return "YES" if Counter(left) == Counter(right) else "NO"​

​230470107061​ ​Python for Data Science​ ​9​


​A.Y. 2025-2026 (ODD)​

​print(is_lapindrome("abccab"))​
​print(is_lapindrome("rotor"))​
​print(is_lapindrome("xyzxy"))​
​print(is_lapindrome("abbaab"))​
​Output:​
​YES​
​YES​
​YES​
​NO​

​Quiz-2​
​ . To shuffle the list(say list1) what function do we use ?​
1
​a) [Link]()​
​b) shuffle(list1)​
​c) [Link](list1)​
​d) [Link](list1)​

​Ans: c) [Link](list1)​

​2. What will be the output?​


​>>>t=(1,2,4,3)​
​>>>t[1:-1]​
​ ) (1, 2)​
a
​b) (1, 2, 4)​
​c) (2, 4)​
​d) (2, 4, 3)​
​Ans: c) (2, 4)​

​ . What will be the output of the following Python code? a=[13,56,17] [Link]([87])​
3
​[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]]​
​Ans: a. 13, 56, 17, [87], 45, 67]​

​230470107061​ ​Python for Data Science​ ​10​


​A.Y. 2025-2026 (ODD)​

​ . Find the output of the following program: nameList = ['abc', 'xyz', 'pqr', 'def'] pos =​
4
​[Link]("Dip") print (pos * 3)​
​a. Dip Dip Dip​
​b. abc abc abc​
​c. xyz xyz xyz​
​d. ValueError: 'Dipesh' is not in list​
​Ans: 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}​
​d. {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}​
​Ans: 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​
​Ans:​​a. mytuple = ("apple", "banana", "cherry")​

​230470107061​ ​Python for Data Science​ ​11​


​A.Y. 2025-2026 (ODD)​

​Assignment 3​​To Perform fundamental scientific computing using Numpy.​


​1.​ T​ o perform numpy operation by using sample data.​
​Code:​
​import numpy as np​
​data = [Link]([10, 20, 30, 40, 50])​
​print("Original Array:", data)​
​print("Array + 5:", data + 5)​
​print("Array * 2:", data * 2)​
​print("Mean:", [Link](data))​
​print("Max:", [Link](data))​
​print("Min:", [Link](data))​
​print("First 3 elements:", data[:3])​
​Output:​
​Original Array: [10 20 30 40 50]​
​Array + 5: [15 25 35 45 55]​
​Array * 2: [ 20 40 60 80 100]​
​Mean: 30.0​
​Max: 50​
​Min: 10​
​First 3 elements: [10 20 30]​

​2.​ Y
​ ou 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 .​

I​nput 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.​

​ rint the concatenated array of size (N+M) X P.​


P
​Sample Input​

​ 3 2​
4
​1 2​
​1 2​
​1 2​
​1 2​
​3 4​
​3 4​
​3 4​

​230470107061​ ​Python for Data Science​ ​12​


​A.Y. 2025-2026 (ODD)​

​Sample Output​

[​ [1 2]​
​[1 2]​
​[1 2]​
​[1 2]​
​[3 4]​
​[3 4]​
​[3 4]]​

​Code:​

​import numpy as np​


​N, M, P = map(int, input().split())​
​arr1 = [Link]([list(map(int, input().split())) for _ in range(N)])​
​arr2 = [Link]([list(map(int, input().split())) for _ in range(M)])​
​result = [Link]((arr1, arr2), axis=0)​
​print(result)​
​Output:​
​2 2 2​
​1 1​
​2 2​
​1 1​
​2 2​
​[[1 1]​
​[2 2]​
​[1 1]​
​[2 2]]​

​Quiz-3​
​1. Why NumPy is used in Python?​

​NumPy is used in Python for efficient numerical and scientific computing. It provides support for​
​large multidimensional arrays and matrices, along with mathematical functions to operate on​
​these arrays faster than standard Python lists.​

​2. how to create 1D Array using numpy ?​

​import numpy as np​


​arr = [Link]([1, 2, 3, 4, 5])​

​230470107061​ ​Python for Data Science​ ​13​


​A.Y. 2025-2026 (ODD)​

​ . To create sequences of numbers, NumPy provides a function __________ analogous to range​


3
​that returns arrays instead of lists.​
​a. arange​
​b. aspace​
​c. aline​
​d. None of the mentioned​
​Ans: a. arange​

​4. The most important object defined in NumPy is an N-dimensional array type called?​
​a. ndarray​
​b. narray​
​c. nd_array​
​d. darray​
​Ans: a. ndarray​

​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​
​Ans: d. All options are correct​

​ . The ________ function returns its argument with a modified shape, whereas the ________​
6
​method modifies the array itself.​
​a. reshape, resize​
​b. resize, reshape​
​c. reshape2, resize​
​d. None of the mentioned​
​Ans: a. reshape, resize​

​7. what is the use of the zeros() function in Numpy array in python ?​
​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​

​230470107061​ ​Python for Data Science​ ​14​


​A.Y. 2025-2026 (ODD)​

​d. None of the above​


​Ans: a. To make a Matrix with all element 0​

​8. Is python numpy better than lists?​

​ es, NumPy is better than lists for numerical operations because it is faster, uses less memory,​
Y
​supports multi-dimensional arrays, and provides many built-in mathematical and statistical​
​functions.​

​230470107061​ ​Python for Data Science​ ​15​


​A.Y. 2025-2026 (ODD)​

​Assignment 4​​To Perform data importing & conditioning using Numpy and​
​Pandas.​
​1. Create txt file and perform file operation.​
​Code:​
​import numpy as np​
​import pandas as pd​
​import os​
​import shutil​

​# Step 1: Create text file with structured data (CSV-like format)​


​with open("[Link]", "w") as f:​
​[Link]("ID,Name,Age,City\n")​
​[Link]("1,Pradyumna,21,Rajkot\n")​
​[Link]("2,Amit,22,Ahmedabad\n")​
​[Link]("3,Ravi,23,Surat\n")​

​print("File created successfully!")​

​# Step 2: Read file with Pandas​


​df = pd.read_csv("[Link]")​
​print("\n Data read using Pandas:")​
​print(df)​

​# Step 3: Append new row to file​


​with open("[Link]", "a") as f:​
​[Link]("4,Karan,24,Vadodara\n")​

​# Read again​
​df_updated = pd.read_csv("[Link]")​
​print("\n Updated Data after appending:")​
​print(df_updated)​

​# Step 4: Convert DataFrame into NumPy array​


​np_data = df_updated.to_numpy()​
​print("\n Data as NumPy Array:")​
​print(np_data)​

​230470107061​ ​Python for Data Science​ ​16​


​A.Y. 2025-2026 (ODD)​

​# Step 5: File operations (copy, rename, delete)​


​[Link]("[Link]", "sample_copy.txt") # Copy​
​[Link]("sample_copy.txt", "sample_backup.txt") # Rename​
​[Link]("sample_backup.txt") # Delete​
​print("\n Copy, Rename and Delete operations completed.")​

​ utput:​
O
​File created successfully!​

​Data read using Pandas:​


​ID Name Age City​
​0 1 Pradyumna 21 Rajkot​
​1 2 Amit 22 Ahmedabad​
​2 3 Ravi 23 Surat​

​Updated Data after appending:​


​ID Name Age City​
​0 1 Pradyumna 21 Rajkot​
​1 2 Amit 22 Ahmedabad​
​2 3 Ravi 23 Surat​
​3 4 Karan 24 Vadodara​

​Data as NumPy Array:​


​[[1 'Pradyumna' 21 'Rajkot']​
​[2 'Amit' 22 'Ahmedabad']​
​[3 'Ravi' 23 'Surat']​
​[4 'Karan' 24 'Vadodara']]​

​Copy, Rename and Delete operations completed.​

​ . Use pandas library to create series and dataframe from various format(Structured data​
2
​form)​
​Code:​
​import pandas as pd​
​import numpy as np​

​# Create Series from Python list​


​data_list = [10, 20, 30, 40, 50]​
​series_from_list = [Link](data_list, name="Numbers")​

​230470107061​ ​Python for Data Science​ ​17​


​A.Y. 2025-2026 (ODD)​

​print("Series from List:\n")​


​print(series_from_list)​

​# Create NumPy array​


​np_array = [Link]([5, 15, 25, 35, 45])​
​series_from_numpy = [Link](np_array, name="ArrayNumbers")​
​print("\n Series from NumPy Array:\n")​
​print(series_from_numpy)​

​# Dictionary to DataFrame​
​data_dict = {​
​"ID": [1, 2, 3],​
​"Name": ["Pradyumna", "Amit", "Ravi"],​
​"Age": [21, 22, 23],​
​"City": ["Rajkot", "Ahmedabad", "Surat"]​
​}​
​df_from_dict = [Link](data_dict)​
​print("\n DataFrame from Dictionary:\n")​
​print(df_from_dict)​

​# First create a sample CSV file​


​df_from_dict.to_csv("sample_data.csv", index=False)​

​# Read CSV into DataFrame​


​df_from_csv = pd.read_csv("sample_data.csv")​
​print("\n DataFrame from CSV File:\n")​
​print(df_from_csv)​

​# Create JSON data​


​json_data = '[{"ID": 1, "Product": "Book", "Price": 150}, {"ID": 2, "Product": "Pen", "Price": 20}]'​

​# Convert JSON → DataFrame​


​df_from_json = pd.read_json(json_data)​
​print("\n DataFrame from JSON String:\n")​
​print(df_from_json)​

​# NumPy 2D array​
​np_matrix = [Link]([[1, "Laptop", 50000], [2, "Phone", 30000], [3, "Tablet", 20000]])​

​230470107061​ ​Python for Data Science​ ​18​


​A.Y. 2025-2026 (ODD)​

​# DataFrame from NumPy array​


​df_from_numpy = [Link](np_matrix, columns=["ID", "Product", "Price"])​
​print("\n DataFrame from NumPy 2D Array:\n")​
​print(df_from_numpy)​
​Output:​
​Series from List:​
​0 10​
​1 20​
​2 30​
​3 40​
​4 50​
​Name: Numbers, dtype: int64​

​Series from NumPy Array:​


​0 5​
​1 15​
​2 25​
​3 35​
​4 45​
​Name: ArrayNumbers, dtype: int64​

​DataFrame from Dictionary:​


​ID Name Age City​
​0 1 Pradyumna 21 Rajkot​
​1 2 Amit 22 Ahmedabad​
​2 3 Ravi 23 Surat​

​DataFrame from CSV File:​


​ID Name Age City​
​0 1 Pradyumna 21 Rajkot​
​1 2 Amit 22 Ahmedabad​
​2 3 Ravi 23 Surat​

​DataFrame from JSON String:​


​ID Product Price​
​0 1 Book 150​
​1 2 Pen 20​

​230470107061​ ​Python for Data Science​ ​19​


​A.Y. 2025-2026 (ODD)​

​DataFrame from NumPy 2D Array:​


​ID Product Price​
​0 1 Laptop 50000​
​1 2 Phone 30000​
​2 3 Tablet 20000​

​ . Handle unstructured data using skimage and matplotlib​


3
​Code:​
​from skimage import io, color, filters, transform​
​import [Link] as plt​
​from [Link] import files​

​# Step 1: Upload image​


​uploaded = [Link]() # You will choose an image from your computer​

​# Step 2: Read uploaded image​


​filename = list([Link]())[0]​
​image = [Link](filename)​

​# Step 3: Show Original Image​


​[Link](figsize=(6,6))​
​[Link](image)​
​[Link]("Original Image")​
​[Link]("off")​
​[Link]()​

​# Step 4: Convert to Grayscale​


​gray_img = color.rgb2gray(image)​
​[Link](figsize=(6,6))​
​[Link](gray_img, cmap="gray")​
​[Link]("Grayscale Image")​

​230470107061​ ​Python for Data Science​ ​20​


​A.Y. 2025-2026 (ODD)​

​[Link]("off")​
​[Link]()​

​# Step 5: Apply Edge Detection​


​edges = [Link](gray_img)​
​[Link](figsize=(6,6))​
​[Link](edges, cmap="gray")​
​[Link]("Edge Detection (Sobel Filter)")​
​[Link]("off")​
​[Link]()​

​# Step 6: Resize Image​


​resized_img = [Link](image, (150, 150))​
​[Link](figsize=(4,4))​
​[Link](resized_img)​
​[Link]("Resized Image (150x150)")​
​[Link]("off")​
​[Link]()​
​Output:​

​230470107061​ ​Python for Data Science​ ​21​


​A.Y. 2025-2026 (ODD)​

​ . Find the duplicate and records in sample dataset.​


4
​[Link]
​Code:​
​import pandas as pd​

​# Step 1: Create sample dataset with duplicates​


​data = {​
​"ID": [1, 2, 2, 3, 4, 4, 5],​
​"Name": ["Pradyumna", "Amit", "Amit", "Ravi", "Karan", "Karan", "Mehul"],​
"​ City": ["Rajkot", "Ahmedabad", "Ahmedabad", "Surat", "Vadodara", "Vadodara",​
​"Bhavnagar"]​
​}​

​df = [Link](data)​
​print("Original Dataset with Duplicates:\n")​
​print(df)​

​230470107061​ ​Python for Data Science​ ​22​


​A.Y. 2025-2026 (ODD)​

​# Step 2: Find duplicate records​


​duplicates = df[[Link]()]​
​print("\nDuplicate Records:\n")​
​print(duplicates)​

​# Step 3: Remove duplicates​


​df_cleaned = df.drop_duplicates()​
​print("\nDataset After Removing Duplicates:\n")​
​print(df_cleaned)​

​# Step 4: Check if duplicates still exist​


​print("\nNumber of duplicates left:", df_cleaned.duplicated().sum())​
​Output:​
​Original Dataset with Duplicates:​
​ID Name City​
​0 1 Pradyumna Rajkot​
​1 2 Amit Ahmedabad​
​2 2 Amit Ahmedabad​
​3 3 Ravi Surat​
​4 4 Karan Vadodara​
​5 4 Karan Vadodara​
​6 5 Mehul Bhavnagar​

​Duplicate Records:​
​ID Name City​
​2 2 Amit Ahmedabad​
​5 4 Karan Vadodara​

​Dataset After Removing Duplicates:​

​230470107061​ ​Python for Data Science​ ​23​


​A.Y. 2025-2026 (ODD)​

​ID Name City​


​0 1 Pradyumna Rajkot​
​1 2 Amit Ahmedabad​
​3 3 Ravi Surat​
​4 4 Karan Vadodara​
​6 5 Mehul Bhavnagar​

​Number of duplicates left: 0​

​Quiz-4​
​1. Mention the different types of Data Structures in Pandas​

​Pandas mainly provides two primary data structures:​

​●​ ​Series → 1D labeled array (like a single column).​

​●​ ​DataFrame → 2D labeled tabular data (like a table with rows & columns).​

​●​ ​(Panel existed earlier for 3D data but is deprecated** in modern Pandas**).​

​2. List some alternatives of Python Pandas​

​Some popular alternatives to Pandas are:​

​●​ ​Polars – Fast DataFrame library written in Rust​

​●​ ​Vaex – For lazy, out-of-core dataframes (handles big data)​

​●​ ​Dask – Parallel computing and large dataset support​

​●​ ​Modin – Scales Pandas across multiple CPUs/cores​

​●​ ​Koalas – Pandas-like API on Apache Spark​

​ . Which of the following indexing capabilities is used as a concise means of selecting data​
3
​from a pandas object?​
​a. In​

​230470107061​ ​Python for Data Science​ ​24​


​A.Y. 2025-2026 (ODD)​

​b. ix​
​c. ipy​
​d. iy​
​Ans: b. Ix​

​4. Which function are used to find missing values in data ?​


​a. isnull()​
​b. isna()​
​c. isnulls()​
​d. None of the mentioned​
​Ans: a. isnull() and b. isna()​

​5. Which of the following function gives information about top level data using Pandas?​
​a. head​
​b. tail​
​c. summary​
​d. none of the mentioned​
​Ans: a. head​
​ . What will be output for the following code? import pandas as pd import numpy as np s =​
6
​[Link]([Link](4)) print([Link])​
​a. 0​
​b. 1​
​c. 2​
​d. 3​
​Ans: b. 1​

​7. In pandas, Index values must be?​


​a. unique​
​b. hashable​
​c. Both A & B​
​d. None of the above​
​Ans: c. Both A & B​

​230470107061​ ​Python for Data Science​ ​25​


​A.Y. 2025-2026 (ODD)​

​8. What is Reindexing in pandas?​

​ eindexing is the process of changing the row/column labels of a DataFrame or Series to match​
R
​a new set of labels. If a label is missing in the original data, Pandas will insert NaN for that​
​position.​

​230470107061​ ​Python for Data Science​ ​26​


​A.Y. 2025-2026 (ODD)​

​Assignment 5​​To Perform shaping of data using Python​


​ . Data shaping & reshaping using NumPy.​
1
​Code:​
​import numpy as np​

​ Create a NumPy array​


#
​arr = [Link](1, 13) # Array with values 1 to 12​
​print("Original Array:\n", arr)​

​ Reshape into 3x4 matrix​


#
​reshaped = [Link](3, 4)​
​print("\nReshaped Array (3x4):\n", reshaped)​

​ Flatten back into 1D array​


#
​flattened = [Link]()​
​print("\nFlattened Back to 1D:\n", flattened)​

​ Reshape into 2x2x3 (3D array)​


#
​reshaped_3d = [Link](2, 2, 3)​
​print("\nReshaped into 3D Array (2x2x3):\n", reshaped_3d)​
​Output:​
​Original Array:​
​[ 1 2 3 4 5 6 7 8 9 10 11 12]​

​Reshaped Array (3x4):​


​[[ 1 2 3 4]​
​[ 5 6 7 8]​
​[ 9 10 11 12]]​

​Flattened Back to 1D:​


​[ 1 2 3 4 5 6 7 8 9 10 11 12]​

​Reshaped into 3D Array (2x2x3):​


​[[[ 1 2 3]​
​[ 4 5 6]]​

​[[ 7 8 9]​
​[10 11 12]]]​

​230470107061​ ​Python for Data Science​ ​27​


​A.Y. 2025-2026 (ODD)​

​ . Perform the slicing , dicing, sorting and shuffling operation on NumPy array.​
2
​Code:​
​# Create a sample 1D array​
​arr = [Link]([10, 20, 30, 40, 50, 60])​
​print("Original Array:", arr)​

​ Slicing​
#
​print("\nSlicing (arr[1:4]):", arr[1:4]) # elements from index 1 to 3​

​ Dicing (For 2D array)​


#
​matrix = [Link](1, 17).reshape(4, 4)​
​print("\nOriginal 4x4 Matrix:\n", matrix)​

​ Extracting sub-matrix (Dicing)​


#
​sub_matrix = matrix[1:3, 1:3] # rows 1-2, cols 1-2​
​print("\nDiced Sub-Matrix (2x2):\n", sub_matrix)​

​ Sorting​
#
​unsorted_arr = [Link]([40, 10, 30, 20])​
​sorted_arr = [Link](unsorted_arr)​
​print("\nSorted Array:", sorted_arr)​

​ Shuffling (randomizes order)​


#
​[Link](unsorted_arr)​
​print("\nShuffled Array:", unsorted_arr)​
​Output:​
​Original Array: [10 20 30 40 50 60]​

​Slicing (arr[1:4]): [20 30 40]​

​Original 4x4 Matrix:​


​[[ 1 2 3 4]​
​[ 5 6 7 8]​
​[ 9 10 11 12]​
​[13 14 15 16]]​

​Diced Sub-Matrix (2x2):​


​[[ 6 7]​
​[10 11]]​

​Sorted Array: [10 20 30 40]​

​230470107061​ ​Python for Data Science​ ​28​


​A.Y. 2025-2026 (ODD)​

​Shuffled Array: [30 40 20 10]​

​ . Perform the task for categorical variable and aggregation of the data.​
3
​Code:​
​import pandas as pd​

​ Create sample DataFrame with categorical variable​


#
​data = [Link]({​
​"Name": ["Amit", "Amit", "Ravi", "Ravi", "Karan"],​
​"Department": ["IT", "IT", "HR", "HR", "Finance"],​
​"Salary": [30000, 35000, 28000, 32000, 40000]​
​})​

​print("Original DataFrame:\n", data)​

​ Convert Department into category type​


#
​data["Department"] = data["Department"].astype("category")​
​print("\nData Types After Categorical Conversion:\n", [Link])​

​ Aggregation - Calculate mean salary per department​


#
​agg_data = [Link]("Department")["Salary"].mean()​
​print("\nAverage Salary by Department:\n", agg_data)​
​Output:​
​Original DataFrame:​
​Name Department Salary​
​0 Amit IT 30000​
​1 Amit IT 35000​
​2 Ravi HR 28000​
​3 Ravi HR 32000​
​4 Karan Finance 40000​

​Data Types After Categorical Conversion:​


​Name object​
​Department category​
​Salary int64​
​dtype: object​

​Average Salary by Department:​


​Department​
​Finance 40000.0​
​HR 30000.0​
​IT 32500.0​

​230470107061​ ​Python for Data Science​ ​29​


​A.Y. 2025-2026 (ODD)​

​Name: Salary, dtype: float64​

​ . Demonstrate the usage of datetime and timedelta function in data science project.​
4
​Code:​
​import pandas as pd​
​from datetime import datetime, timedelta​

​ Create sample dates​


#
​today = [Link]()​
​print("Today's Date:", today)​

​ Add 10 days using timedelta​


#
​future_date = today + timedelta(days=10)​
​print("\nDate After 10 Days:", future_date)​

​ Create Pandas date range​


#
​date_range = pd.date_range(start="2024-01-01", periods=5, freq="D")​
​print("\nDate Range (5 Days):\n", date_range)​

​ Example: Calculate difference between dates​


#
​date_df = [Link]({​
​"Start": pd.to_datetime(["2024-01-01", "2024-02-01"]),​
​"End": pd.to_datetime(["2024-01-10", "2024-02-20"])​
​})​

​ ate_df["Difference"] = date_df["End"] - date_df["Start"]​


d
​print("\nDate Difference using Timedelta:\n", date_df)​
​Output:​
​Today's Date: 2025-09-12 23:40:12.123456​

​Date After 10 Days: 2025-09-22 23:40:12.123456​

​Date Range (5 Days):​


​DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03',​
​'2024-01-04', '2024-01-05'],​
​dtype='datetime64[ns]', freq='D')​

​Date Difference using Timedelta:​


​Start End Difference​
​0 2024-01-01 2024-01-10 9 days​
​1 2024-02-01 2024-02-20 19 days​

​230470107061​ ​Python for Data Science​ ​30​


​A.Y. 2025-2026 (ODD)​

​Quiz-5​
​1. What is Time Series in Pandas?​

T​ ime Series in Pandas is a sequence of data points indexed by timestamps or dates. It allows​
​easy handling of time-based data, resampling, shifting, and date-range generation.​

​2. Which library can be used to plot geographical data ?​


​a. basemap​
​b. geomap​
​c. sklearn​
​d. None of the mentioned​
​Ans: a. Basemap​

​3. Which are not correct property for Pie Chart plotting in matplotlib?​
​a. explode​
​b. autopct​
​c. align​
​d. None of the mentioned​
​Ans: c. align​

​4. Which are not correct marker for line appreance in matplotlib?​
​a. s​
​b. p​
​c. A​
​d. None of the mentioned​
​Ans: c. A​

​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​
​Ans: b. [Link]()​

​230470107061​ ​Python for Data Science​ ​31​


​A.Y. 2025-2026 (ODD)​

​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​
​Ans: d. All of the mentioned​

​7. Which library would you prefer for plotting in Python language: Seaborn or Matplotlib?​

​It depends on use case:​

​●​ S
​ eaborn​​→ Better for statistical visualization, attractive​​default styles, easier for quick​
​plots.​

​●​ M
​ atplotlib​​→ More control and customization, supports​​complex visualizations.​
​For most data science tasks →​​Seaborn​​is preferred​​for quick and beautiful plots.​

​230470107061​ ​Python for Data Science​ ​32​

You might also like