Pythonfile
Pythonfile
Pythonfile
Date of
S.No. LAB Topics Remarks
Conduct
1 LAB-1 18/01/24
2 LAB-2 25/01/24
3 LAB-3 01/02/24
4 LAB-4 08/02/24
5 LAB-6 15/02/24
6 LAB-7 22/02/24
7 LAB-9.1 14/03/24
8 LAB-9.2 21/03/24
9 LAB-11 04/04/24
10 LAB-12 11/04/24
4/25/24, 7:13 PM Pythonlab1.ipynb - Colab
Python is a high-level, versatile programming language known for its simplicity and readability.
It's widely used in various fields such as web development, data analysis, artificial intelligence,
and more. The Python shell is an interactive environment where you can execute Python code
line by line. To access the Python shell, you can open a terminal or command prompt and type
python. Once inside the shell, you can execute Python statements and see the results
immediately.
Setting up a development environment is essential for writing and running Python code
efficiently. Anaconda is a distribution of Python that comes bundled with many useful libraries
and tools for data science and scientific computing. To install Anaconda, you can download the
installer from the official website and follow the installation instructions provided. Once installed,
Anaconda provides an integrated development environment (IDE) called Anaconda Navigator,
which allows you to manage packages, environments, and launch applications like Jupyter
Notebook.
Jupyter Notebook is a web-based interactive computing environment that enables you to create
and share documents containing live code, equations, visualizations, and explanatory text. It
supports various programming languages, including Python, R, and Julia. Jupyter Notebooks are
organized into cells, which can contain either code or markdown text. You can execute code
cells individually and see the output immediately below the cell.
To work with Jupyter Notebook, you can launch it from Anaconda Navigator or from the
command line by typing jupyter notebook. This will open a web browser with the Jupyter
dashboard, where you can navigate your files and create new notebooks. To create a new
notebook, click on the "New" button and select "Python 3" (or any other available kernel). You can
then start writing code in the code cells and execute them by pressing Shift + Enter.
https://colab.research.google.com/drive/1R4Ccaa3lMO97vWS8HpYWpvcPN2Wet55B?authuser=1#scrollTo=h2_wjJU5d9JJ&printMode=true 1/2
4/25/24, 7:13 PM Pythonlab1.ipynb - Colab
print("Hello, World!")
Hello, World!
https://colab.research.google.com/drive/1R4Ccaa3lMO97vWS8HpYWpvcPN2Wet55B?authuser=1#scrollTo=h2_wjJU5d9JJ&printMode=true 2/2
1/18/24, 6:54 PM pythonlab2.ipynb - Colaboratory
a=55
b="pYTHON"
c=921.32
print(type(a))
print(type(b))
print(type(c))
<class 'int'>
<class 'str'>
<class 'float'>
https://colab.research.google.com/drive/1dlcBY2XeUrcjJiyYLq1iJQokXzJOSwsC#printMode=true 1/3
1/18/24, 6:54 PM pythonlab2.ipynb - Colaboratory
n = 4
k = n - 1
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")
*
* *
* * *
* * * *
a,b=1,1
i=0
print("Series is:")
for i in range(1,8):
print(a,end=" ")
sum=a+b
a=b
b=sum
Series is:
1 1 2 3 5 8 13
https://colab.research.google.com/drive/1dlcBY2XeUrcjJiyYLq1iJQokXzJOSwsC#printMode=true 2/3
1/18/24, 6:54 PM pythonlab2.ipynb - Colaboratory
https://colab.research.google.com/drive/1dlcBY2XeUrcjJiyYLq1iJQokXzJOSwsC#printMode=true 3/3
1/18/24, 8:10 PM pythonlab3.ipynb - Colaboratory
Ques 1)Write a python program to swap two numbers using a third variable
Ques 2)Write a python program to swap two numbers without using third variable
Code Text
a=int(input("Enter 1st number:"))
b=int(input("Enter 2nd number:"))
print("Numbers before swaping:")
print(a,b)
a=a+b
b=a-b
a=a-b
print("Numbers after swaping:")
print(a,b)
Ques 3)Write a python program to read two numbers and find the sum of their cubes
Ques 4)Write a python program to read three numbers and if any two variables are equal, print that number
Ques 5)Write a python program to read three numbers and find the smallest among them
Ques 6)Write a python program to read three numbers and print them in ascending order (without using sort function)
Ques 7)Write a python program to read radius of a circle and print the area
pi=3.14
r=float(input("Enter the radius"))
print("Area of the circle is",pi*r*r)
Ques 8)Write a python program to read a number ,if it is an even number , print the square of that number and if it is odd number print cube of
that number.
https://colab.research.google.com/drive/1UW9VwZHFQflgC2D4pVXvCrx56k_4AfWw#printMode=true 2/3
1/18/24, 8:10 PM pythonlab3.ipynb - Colaboratory
https://colab.research.google.com/drive/1UW9VwZHFQflgC2D4pVXvCrx56k_4AfWw#printMode=true 3/3
2/15/24, 5:39 PM pythonlan6.ipynb - Colaboratory
Enter a number:2
Count is: 2
Count is: 3
Count is: 4
Count is not less than 5 anymore.
number = 0
count = 0
while True:
if number % 2 == 0:
print(number)
count += 1
if count == 5:
break
number += 1
output 0
2
4
6
8
number = 0
count = 0
while count < 4:
number += 1
if number % 2 != 0:
continue
print(number)
count += 1
2
4
6
8
for i in range(10):
if i == 3:
pass
print(i)
0
1
2
3
4
5
6
7
8
9
https://colab.research.google.com/drive/1c93e78x4Ykfsi_T93L1e8H67aWWdkMgL#scrollTo=qJzrrHNFsnlC&printMode=true 1/3
2/15/24, 5:39 PM pythonlan6.ipynb - Colaboratory
6. Write a Python program to count the number of characters (character frequency) in a string
7. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2,
return instead of the empty string.
8. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first
char itself
9.Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string.
10. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then
add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged.
https://colab.research.google.com/drive/1c93e78x4Ykfsi_T93L1e8H67aWWdkMgL#scrollTo=qJzrrHNFsnlC&printMode=true 2/3
2/15/24, 5:39 PM pythonlan6.ipynb - Colaboratory
input_string = input("Enter a string: ")
if len(input_string) >= 3:
if input_string.endswith("ing"):
modified_string = input_string + "ly"
else:
modified_string = input_string + "ing"
else:
modified_string = input_string
print("Modified string:", modified_string)
https://colab.research.google.com/drive/1c93e78x4Ykfsi_T93L1e8H67aWWdkMgL#scrollTo=qJzrrHNFsnlC&printMode=true 3/3
2/15/24, 6:11 PM lab7.ipynb - Colaboratory
keyboard_arrow_down TUPLE
1. Write a Python program to create a tuple.
(1, 2, 3, 4, 5)
3. Write a Python program to create a tuple with numbers and print one item
Unpacked variables: 1 2 3
7. Write a Python program to get the 4th element and 4th element from last of a tuple
# Program to get the 4th and 4th element from the last of a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
fourth_element = my_tuple[3]
fourth_from_last = my_tuple[-4]
print("4th element:", fourth_element)
print("4th element from last:", fourth_from_last)
4th element: 4
4th element from last: 6
https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 1/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory
10. Write a Python program to check whether an element exists within a tuple.
Index of item 3 : 2
https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 2/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory
keyboard_arrow_down LIST
1. Write a Python program to sum all the items in a list.
my_list = [1, 2, 3, 4, 5]
total = 0
for item in my_list:
total += item
print("Sum of list items:", total)
my_list = [1, 2, 3, 4, 5]
result = 1
for item in my_list:
result *= item
print("Product of list items:", result)
my_list = [1, 2, 3, 4, 5]
largest = max(my_list)
print("Largest number in list:", largest)
my_list = [1, 2, 3, 4, 5]
smallest = min(my_list)
print("Smallest number in list:", smallest)
5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a
given list of strings
Expected Result : 2
# Sample List
sample_list = ['abc', 'xyz', 'aba', '1221']
# Initialize count
count = 0
Expected Result: 2
https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 3/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory
6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
# Sample List
sample_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
my_list = [1, 2, 3, 4, 2, 3, 5]
unique_list = []
for item in my_list:
if item not in unique_list:
unique_list.append(item)
print("List after removing duplicates:", unique_list)
my_list = []
if not my_list:
print("List is empty")
else:
print("List is not empty")
List is empty
original_list = [1, 2, 3, 4, 5]
cloned_list = original_list[:]
print("Cloned list:", cloned_list)
10. Write a Python program to find the list of words that are longer than n from a given list of words.
11. Write a Python function that takes two lists and returns True if they have at least one common member.
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
common_member = False
for item in list1:
if item in list2:
common_member = True
break
print("Do the lists have at least one common member?", common_member)
12. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 4/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory
# Sample List
sample_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 5/5
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory
1. Write a Python program that create a class triangle and define two methods, create_triangle() and print_sides().
class Triangle:
def _init_(self):
self.sides = []
def create_triangle(self):
self.sides = [float(input("Enter side "+str(i+1)+": ")) for i in range(3)]
def print_sides(self):
print("Sides of the triangle are:", self.sides)
# Example usage:
triangle = Triangle()
triangle.create_triangle()
triangle.print_sides()
output Enter
Enter
side 1: 4
side 2: 6
Enter side 3: 1
Sides of the triangle are: [4.0, 6.0, 1.0]
2. Write a Python program to create a class with two methods get_String() and print_String().
class StringManipulator:
def __init__(self):
self.string = ""
def get_String(self):
self.string = input("Enter a string: ")
def print_String(self):
print("String:", self.string)
3. Write a Python program to create a class Rectangle that takes the parameter length and width. The class should also contain a method for
computing its perimeter.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def perimeter(self):
return 2 * (self.length + self.width)
Perimeter of rectangle: 18
4. Write a Python program to create a class Circle that takes the parameter radius. The class should also contain two methods for computing
its area & perimeter respectively. Use constructor to implement initialization of parameters
https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 1/4
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
5.Create a Cricle class and intialize it with radius. Make two methods getArea and getCircumference inside this class.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def getArea(self):
return math.pi * self.radius ** 2
def getCircumference(self):
return 2 * math.pi * self.radius
class Temperature:
def convertFahrenheit(self, celsius):
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius} degrees Celsius is equal to {fahrenheit} degrees Fahrenheit.")
7. Create a Student class and initialize it with name and roll number. Make methods to :
https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 2/4
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory
class Student:
def __init__(self, name, roll_number):
self.name = name
self.roll_number = roll_number
self.age = None
self.marks = None
def display(self):
print("Name:", self.name)
print("Roll Number:", self.roll_number)
if self.age is not None:
print("Age:", self.age)
else:
print("Age not set.")
if self.marks is not None:
print("Marks:", self.marks)
else:
print("Marks not set.")
Initial Information:
Name: John
Roll Number: 101
Age not set.
Marks not set.
Updated Information:
Name: John
Roll Number: 101
Age: 20
Marks: 85
1. Make a method addTime which should take two time object and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min)
3. Make a method DisplayMinute which should display the total minutes in the Time. E.g.- (1 hr 2 min) should display 62 minute.
https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 3/4
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory
class Time:
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes
class StringReverser:
def displayMinute(self):
def reverse_words(self, string):
total_minutes = self.hours * 60 + self.minutes
# Split the string into words
print(f"Total minutes: {total_minutes} minutes")
words = string.split()
# Create instances of the class
# Reverse the list of words
time1 = Time(2, 50)
reversed_words = words[::-1]
time2 = Time(1, 20)
https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 4/4
3/9/24, 7:40 PM Lab-9.2: Object-Oriented Programming - Class Inheritance & Method Overriding.ipynb - Colaboratory
1. Write a Python program that has a class Animal with a method legs(). Create two subclasses Tiger and Dog, access the method leg
explicitly with class Dog and implicitly with the class Tiger.
class Animal:
def legs(self):
print("This animal has 4 legs")
class Tiger(Animal):
pass
class Dog(Animal):
def legs(self):
print("This animal has 4 legs (explicit access)")
tiger = Tiger()
tiger.legs() # Implicit access
dog = Dog()
dog.legs() # Explicit access
2. Write a Python program to create a class Employee. Define two subclasses: Engineer and Manager. Every class should have method named
printDesignation() that prints Engineer for Engineer class and Manager for Manager Class.
class Employee:
def printDesignation(self):
pass
class Engineer(Employee):
def printDesignation(self):
print("Engineer")
class Manager(Employee):
def printDesignation(self):
print("Manager")
engineer = Engineer()
engineer.printDesignation()
manager = Manager()
manager.printDesignation()
Engineer
Manager
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
print(person1.name, person1.age)
print(person2.name, person2.age)
Alice 30
Bob 25
class Parent:
def show(self):
print("Parent method")
class Child(Parent):
def show(self):
print("Child method")
obj = Child()
obj.show() # This will print "Child method"
Child method
class Class1:
def method1(self):
print("Method 1")
https://colab.research.google.com/drive/1AfX5JFL5mV-GpCYx2fi7Fp9A9q7nHI07?authuser=1#scrollTo=zhS1JrZMiX3p&printMode=true 1/2
3/9/24, 7:40 PM Lab-9.2: Object-Oriented Programming - Class Inheritance & Method Overriding.ipynb - Colaboratory
class Class2:
def method2(self):
print("Method 2")
class Class3(Class1, Class2):
pass
obj = Class3()
obj.method1()
obj.method2()
Method 1
Method 2
https://colab.research.google.com/drive/1AfX5JFL5mV-GpCYx2fi7Fp9A9q7nHI07?authuser=1#scrollTo=zhS1JrZMiX3p&printMode=true 2/2
4/25/24, 8:48 PM Lab11.ipynb - Colab
#Upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def read_file(filename):
with open(filename, 'r') as file:
text = file.read()
return text
filename = 'python.txt'
print(read_file(filename))
2. Write a Python program to read a file line by line and store it into a list.
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def read_lines_to_list(filename):
with open(filename, 'r') as file:
lines = file.readlines()
return lines
filename = 'python.txt'
print(read_lines_to_list(filename))
3. Write a Python program to read a file line by line store it into a variable.
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def read_lines_to_variable(filename):
with open(filename, 'r') as file:
content = file.read()
return content
filename = 'python.txt'
content = read_lines_to_variable(filename)
print(content)
4. Write a Python program to read a file line by line store it into an array.
https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 1/5
4/25/24, 8:48 PM Lab11.ipynb - Colab
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def read_lines_to_array(filename):
with open(filename, 'r') as file:
lines = file.readlines()
return [line.strip() for line in lines]
filename = 'python.txt'
print(read_lines_to_array(filename))
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def find_longest_words(filename):
with open(filename, 'r') as file:
words = file.read().split()
max_length = len(max(words, key=len))
return [word for word in words if len(word) == max_length]
filename = 'python.txt'
print(find_longest_words(filename))
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def count_lines(filename):
with open(filename, 'r') as file:
line_count = sum(1 for line in file)
return line_count
filename = 'python.txt'
print(count_lines(filename))
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
from collections import Counter
def count_word_frequency(filename):
with open(filename, 'r') as file:
words = file.read().split()
return Counter(words)
filename = 'python.txt'
print(count_word_frequency(filename))
https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 2/5
4/25/24, 8:48 PM Lab11.ipynb - Colab
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
import os
def get_file_size(filename):
return os.path.getsize(filename)
filename = 'python.txt'
print(get_file_size(filename))
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def write_list_to_file(filename, data):
with open(filename, 'w') as file:
for item in data:
file.write(str(item) + '\n')
filename = 'python.txt'
data = [1, 2, 3, 4, 5]
write_list_to_file(filename, data)
10. Write a Python program to copy the contents of a file to another file.
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def copy_file(source, destination):
with open(source, 'r') as src_file:
with open(destination, 'w') as dest_file:
dest_file.write(src_file.read())
source_file = 'python.txt'
destination_file = 'doc.txt'
copy_file(source_file, destination_file)
11. Write a Python program to combine each line from first file with the corresponding line in second file.
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def combine_files(file1, file2, output_file):
with open(file1, 'r') as f1, open(file2, 'r') as f2, open(output_file, 'w') as out_file:
for line1, line2 in zip(f1, f2):
out_file.write(line1.strip() + ' ' + line2)
file1 = 'python.txt'
file2 = 'jupiter.txt'
output_file = 'doc.txt'
combine_files(file1, file2, output_file)
https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 3/5
4/25/24, 8:48 PM Lab11.ipynb - Colab
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
import random
def read_random_line(filename):
with open(filename, 'r') as file:
lines = file.readlines()
return random.choice(lines)
filename = 'python.txt'
print(read_random_line(filename))
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def is_file_closed(file_obj):
return file_obj.closed
filename = 'python.txt'
file_obj = open(filename, 'r')
print("Is file closed?", is_file_closed(file_obj))
file_obj.close()
print("Is file closed?", is_file_closed(file_obj))
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def remove_newlines(filename):
with open(filename, 'r') as file:
lines = file.readlines()
with open(filename, 'w') as file:
for line in lines:
file.write(line.strip() + '\n')
filename = 'python.txt'
remove_newlines(filename)
15. Write a Python program that takes a text file as input and returns the number of words of a given text file. Note: Some words can be
separated by a comma with no space.
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def count_words(filename):
with open(filename, 'r') as file:
text = file.read()
# Remove commas without spaces
text = text.replace(',', ' ')
words = text.split()
return len(words)
filename = 'python.txt'
print("Number of words:", count_words(filename))
https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 4/5
4/25/24, 8:48 PM Lab11.ipynb - Colab
https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 5/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
a. empty series
d. scalar series
import pandas as pd
import numpy as np
# a. Empty series
empty_series = pd.Series()
print("Empty Series:")
print(empty_series)
print()
# d. Scalar series
scalar_series = pd.Series(5)
print("Scalar Series:")
print(scalar_series)
print()
Scalar Series:
0 5
dtype: int64
https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 1/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
import pandas as pd
import numpy as np
Indexed Series:
one 1
two 2
three 3
four 4
five 5
dtype: int64
one NaN
two NaN
three NaN
four NaN
five NaN
dtype: float64
one 5
two 5
three 5
four 5
five 5
dtype: int64
a. Index names
b. Index numbers
c. Slicing
import pandas as pd
import numpy as np
# a. Retrieve elements from the series using index names
element_using_index_names = series_from_dict['a']
print("Element using index names:", element_using_index_names)
# c. Slicing
sliced_elements = series_from_array[1:3]
print("Sliced elements:")
print(sliced_elements)
print()
a. Empty DataFrame
https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 2/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
import pandas as pd
import numpy as np
# a. Empty DataFrame
empty_df = pd.DataFrame()
print("Empty DataFrame:")
print(empty_df)
print()
Empty DataFrame:
Empty DataFrame
Columns: []
Index: []
import pandas as pd
import numpy as np
df_from_list['Column3'] = [4, 5, 6]
df_from_list['Column4'] = ['d', 'e', 'f']
print("DataFrame with 3-4 columns:")
print(df_from_list)
print()
import pandas as pd
import numpy as np
print("DataFrame with index:")
print(df_from_list)
print()
https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 3/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
0 1 a 4 d
1 2 b 5 e
2 3 c 6 f
7. Display all the values from the DataFrame mentioned in Q6 using index and index name for :
import pandas as pd
import numpy as np
import pandas as pd
import numpy as np
# a. Display all the values from the DataFrame mentioned in Q6 using index and index name for the second row values
second_row_values_by_index = df_from_list.iloc[1]
second_row_values_by_index_name = df_from_list.loc['two']
print("Second row values by index:")
print(second_row_values_by_index)
print("\nSecond row values by index name:")
print(second_row_values_by_index_name)
# b. Display all the values from the DataFrame mentioned in Q6 using index and index name for the second column values
second_column_values_by_index = df_from_list.iloc[:, 1]
second_column_values_by_name = df_from_list['Column2']
print("\nSecond column values by index:")
print(second_column_values_by_index)
print("\nSecond column values by name:")
print(second_column_values_by_name)
import pandas as pd
import numpy as np
sliced_df = df_from_list.iloc[2:4]
print("Sliced DataFrame:")
print(sliced_df)
print()
Sliced DataFrame:
Column1 Column2 Column3 Column4
2 3 c 6 f
9. Delete a row
import pandas as pd
i t
https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 4/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
import numpy as np
df_after_row_deletion = df_from_list.drop('three', axis=0, errors='ignore')
print("DataFrame after row deletion:")
print(df_after_row_deletion)
print()
import pandas as pd
import numpy as np
df_after_column_deletion = df_from_list.drop('Column4', axis=1)
print("DataFrame after column deletion:")
print(df_after_column_deletion)
https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 5/5