0% found this document useful (0 votes)
0 views

Chirjot Singh_24055 Python File

Uploaded by

chirjotsinghdung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Chirjot Singh_24055 Python File

Uploaded by

chirjotsinghdung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Practical File

BMS I YEAR - I SEMESTER


PYTHON AND DATA FUNDAMENTALS FILE

Shaheed Sukhdev College of Business Studies


[University of Delhi]
Grade “A” Accredited by NAAC

Submitted By:-
CHIRJOT SINGH
24055
BMS 1-C

1
INDEX
Practical Date S. No Topic Question Pg. No.
1.1 Print Method Print text “Hello World”
1 06/09/24 Arithmetic 04
1.2 Basic Arithmetic Operations on numbers
Operators
2.1 Arithmetic Calculating Simple and Compound Interest
2 10/09/24 05-06
2.2 Operators Area Of Regular Shapes
3.1 Table of a Number
3.2 Odd Numbers in a Range
3 14/09/24 FOR Loop 07-08
3.3 Even Numbers in a Range
3.4 Power Of Variable entered by User
4.1 Divisibility Test for 5
4 24/09/24 4.2 IF ELIF ELSE Identify if it is a Leap Year 09-10
4.3 Allocation of Grade according to Score
5 25/09/24 5 IF ELIF ELSE Amount To Be Charged On Baggage 11
6.1 Table of a Number using WHILE Loop
6 26/09/24 6.2 WHILE Loop Sum of first ‘n’ Natural Numbers 12-13
6.3 Enter Password till Correct
Get Inputs And Tell How No. Of Multiples
7 01/10/24 7 WHILE Loop 14
of 5
8 03/10/24 8 FOR Loop Multiplication Of Matrices 15
9.1 WHILE Loop Square of Numbers from 1 to 5
9 10/10/24 9.2 Filter people younger than 18 15-17
LISTS
9.3 Sum of Integers entered by User
10.1 Elements Present In One List But Not Other
Find Max and Min Element In Set And
10.2
Power Set
10.3 SETS Remove duplicates from List
10 15/10/24 18-19
10.4 Check if Sets are Disjoint
10.5 Creating a Power Set
10.6 DICTIONARY Arrange Dictionary in Ascending Order
11.1 Frequency Count in Dictionary
11.2 DICTIONARY Find Key with Maximum Value
11.3 Convert 2 lists into a Dictionary
11 17/10/24 20-21
11.4 Function Reverse Order of a Sentence
11.5 Definition Reverse A List
11.6 Sort A List
12.1 Function Return Index of a Target
12 18/10/24 22-25
12.2 Definition Convert String to Uppercase
2
12.3 Remove duplicates from List
12.4 Factorial of a Number
Recursion
12.5 Add 'a' to itself 'b' times
12.6 Sum of variable number of Arguments
Function
12.7 Return Full Name using First and Last name
Definition
12.8 Area of Circle
13.1 Class for SI and CI
13 22/10/24 Classes 26-27
13.2 Class for area of rectangle
14.1 Function Identify if Number is Prime
14 23/10/24 28-29
14.2 Definition Maximum of 3 Numbers
15.1 Area of Rectangle using Module
15 05/11/24 Python Modules 30-31
15.2 Record Transactions with Date
16 07/11/24 16 Classes Create Class for Adding 2 Numbers 32
Take 1D Array Argument and return 1D
17 14/11/24 17 Arrays Array Argument containing only positive 33
elements of input Array
18.1 Bar Graph
18.2 Line Graph
18 19/11/24 18.3 MATPLOTLIB Pie Graph 34-38
18.4 Histogram
18.5 Scatter Plot
19.1 Read a csv. file
22/11/24 DATA
19 19.2 Overwriting an existing file 39-40
HANDLING
19.3 Lines starting with A or E only
20.1 Create A Series And Multiply By 2
20.2 Basic Operations On 2 Series
20.3 Create Data Frame
20.4 Retrieve Data From File
20.5 SERIES AND Combine 2 Data Frame
20 28/11/24 DATAFRAME 41-47
20.6 Combining Using Merge
20.7 Combine Common Rows
20.8 Using Outer And Inner In Data Frame
20.9 Rename Columns While Using Outer Join
20.10 Right And Left Join
PANDAS
21 5/12/24 21 Performing Functions On Given Set Of Data 48-50
LIBRARY
22.1 MIXED Palindrome
22 19/12 51-52
22.2 QUESTIONS Prime No. Between Ranges

3
1.1 Print text “Hello World” 06/09/2024
print (“Hello World”)
Output
Hello World

1.2 Basic Arithmetic Operations on numbers


x = int(input("x = "))
y = int(input("y = "))
print ("sum = ",x+y)
print ("difference = ",x-y)
print ("product = ",x*y)
print ("division = ",x/y)
print ("floor division = ",x//y)
print ("modulus = ",x%y)
Output
x=7
y=7
sum = 14
difference = 0
product = 49
division = 1.0
floor division = 1
modulus = 0

4
2.1 Calculating Simple and Compound Interest 10/09/2024
p = int(input("Principle Amount = "))
r = float(input("ROI = "))
t = float(input("Time (in years) = "))
print ("Simple Interest = ",(p*r*t)/100)
print ("Compound Interest = ",p*((1+(r/100))**t)- p)
Output
Principle Amount = 4500
ROI = 14
Time (in years) = 2
Simple Interest = 1260.0
Compound Interest = 1348.2000000000016

2.2 Area Of Regular Shapes


print ("Enter dimensions for triangle")
b = int(input("Base = "))
h = int(input("Height = "))
print ("Area of triangle = ",0.5*b*h)
print ("Enter dimensions for circle")
r = int(input("Radius = "))
p = float(input("Pi = "))
print ("Area of circle = ",p*(r)**2)
print ("Enter dimensions for square")
a = int(input("Side = "))
print ("Area of square = ",a**2)
print ("Enter dimensions for rectangle")
l = int(input("Length = "))
t = int(input("Breadth = "))
print ("Area of rectangle = ",l*t)
Output
Enter dimensions for triangle
Base = 7

5
Height = 7
Area of triangle = 24.5
Enter dimensions for circle
Radius = 6
Pi = 3.14
Area of circle = 113.04
Enter dimensions for square
Side = 4
Area of square = 16
Enter dimensions for rectangle
Length = 45
Breadth = 54
Area of rectangle = 2430

6
3.1 Table of a Number 14/09/2024
n = int(input("Enter a number = "))
for x in range (1,11,1) :
print (n*x)
Output
Enter a number = 45
45
90
135
180
225
270
315
360
405
450
3.2 Odd Numbers in a Range
l = int(input("Enter Odd Lower Limit = "))
u = int(input("Enter Upper Limit = "))
print ("Odd values between ",l," and ",u, "are as follows :")
for x in range (l,u,2) :
print (x)
Output
Enter Odd Lower Limit = 3
Enter Upper Limit = 7
Odd values between 3 and 7 are as follows :
3
5

3.3 Even Numbers in a Range


l = int(input("Enter Even Lower Limit = "))

7
u = int(input("Enter Upper Limit = "))
print ("Even values between ",l," and ",u, "are as follows :")
for x in range (l,u,2) :
print (x)
Output
Enter Even Lower Limit = 2
Enter Upper Limit = 8
Even values between 2 and 8 are as follows :
2
4
6

3.4 Power Of Variable entered by User – 14/09/2024


n = int(input("Enter a number = "))
l = int(input("Enter Limit of Power = "))
for x in range (l+1) :
print (n**x)
Output
Enter a number = 14
Enter Limit of Power = 2
1
14
196

8
4.1 Divisibility Test for 5 24/09/2024
n = int(input("Enter a number = "))
if n%5==0 :
print(n,” is divisible by 5”)
else :
print(n,”isn’t divisible by 5”)
Output
Enter a number = 75
75 is divisible by 5

4.2 Identify if it is a Leap Year


year = 2022
if year % 400 == 0:
print(f"{year} is a leap year.")
elif year % 100 == 0:
print(f"{year} is not a leap year.")
elif year % 4 == 0:
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Output
2022 is not a leap year.
4.3 Allocation of Grade using Score
p = int(input("Enter score (in %) = "))
if p == 100 :
print ("A+")
elif 90 <= p < 100 :
print ("A")
elif 80 <= p < 90 :
print ("B")

9
elif 70 <= p < 80 :
print ("C")
elif 60 <= p < 70 :
print ("D")
else :
print ("F")
Output
Enter score (in %) = 56
F

10
5. Amount To Be Charged On Baggage 25/09/2024
w = int(input("Enter weight of baggage = "))
if w <= 25 :
k = 1000
else :
k = (w-25)*100+1000
print ("Please pay ",k," rupees")
Output
Enter weight of baggage = 45
Please pay 3000 rupees

11
6.1 Table of a Number using WHILE Loop 26/09/2024
n = int(input("Enter a number = "))
l=1
while l<=10 :
print(n,"x",l,"=",n*l)
l+=1
Output
Enter a number = 4
4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

6.2 Sum of first ‘n’ Natural Numbers


n = int(input("Enter a number = "))
i=0
s=0
while i<n :
i+=1
s+=i
print (s)
Output
Enter a number = 5
15
12
6.3 Enter Password till Correct
p = str(input("Enter Password = "))
while p != "chirjot1" :
if p != "chirjot1" :
print ("Incorrect Password")
p = str(input("Try Again = "))
print ("Correct Password")
Output
Enter Password = chirjo
Incorrect Password
Try Again = chirjot1
Correct Password

13
7. Get Inputs And Tell How No. Of Multiples of 5 01/10/2024
y = []
n=1
while n<11 :
x = int(input("Enter a number - "))
m=x%5
y.append(m)
n+=1
k = y.count(0)
print(k ,"numbers are divisble by 5")
Output
Enter a number - 45
Enter a number - 62
Enter a number - 15
Enter a number - 35
Enter a number - 84
Enter a number - 57
Enter a number - 45
Enter a number - 65
Enter a number - 25
Enter a number - 41
6 numbers are divisble by 5

14
8. Multiplication Of Matrices 03/10/2024
a = [[2,3],[1,5]]
b = [[6,8],[9,4]]
mat=[[0,0],[0,0]]
for i in range (len(a)):
for j in range (len(b[0])) :
for k in range (len(b)) :
mat[i][j]+= a[i][k]*b[k][j]
for r in mat :
print (r)
Output
[39, 28]
[51, 28]

15
9.1 Squares of Numbers from 1 to 20 10/10/2024
n=1
x=[]
while n<21 :
k=n**2
x.append(k)
n+=1
print(x)
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

9.2 Filter people younger than 18


x = [15,22,19,17,26,30,18,14]
l = [i for i in x if i<18]
print (l)
Output
[15, 17, 14]

9.3 Sum of Integers entered by User


x = int(input("How Many Integers Would You Like To Enter ? - "))
n=0
k=0
z=[]
if x==0 :
print ("SUM = 0")
else :
while n<x :
y = int(input("Enter an Integer - "))
k+=y
z.append(y)
16
n+=1
print ("Integers Entered = ",z)
print ("SUM = ",k)
Output
How Many Integers Would You Like To Enter ? - 7
Enter an Integer - 4
Enter an Integer - 5
Enter an Integer - 6
Enter an Integer - 4
Enter an Integer - 7
Enter an Integer - 8
Enter an Integer - 89
Integers Entered = [4, 5, 6, 4, 7, 8, 89]
SUM = 123

17
10.1 Elements Present In One List But Not Other 15/10/2024
x = [1,3,4,5]
y = [2,3,5,7]
s1 = set(x)
s2 = set(y)
print (s1-s2,"is not present in S2")
print (s2-s1,"is not present in S1")
Output
{1, 4} is not present in S2
{2, 7} is not present in S1

10.2 Find Max and Min Element In Set And Power Set
s = {1,2,3}
a = min(s)
b = max(s)
print (a,"is minimum element and",b,"is maximum element")
Output
1 is minimum element and 3 is maximum element

10.3 Remove duplicates from List


l = [1,2,3,3,4,2,2,1]
k = list(set(l))
print(k)
Output
[1, 2, 3, 4]

10.4 Check if Sets are Disjoint


a = {1,2,3,4,5}
b = {6,7,8,9,10}
c = set ()
if a&b == c :
18
print("a and b are disjoint sets")
else :
print("a and b aren't disjoint sets")
Output
a and b are disjoint sets

10.5 Creating a Power Set


s = {1,2,3}
p = [set()]
for x in s :
p+=[subset|{x} for subset in p]
print("power set – ",p)
Output
power set – [set(), {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}]

10.6 Arrange Dictionary in Ascending Order


d1 ={1:"a",3:"c",5:"e",4:"d"}
lst1=list(d1.keys())
print(lst1)
lst1.sort()
print(lst1)
Output
[1, 3, 5, 4]
[1, 3, 4, 5]

19
11.1 Frequency Count in Dictionary 17/10/2024
d = {1:"Dog",2:"Cat", 3:"Dog", 4:"Elephant"}
count = {}
for v in d.values():
if(not(v in count)):
count[v] = 0
count[v] += 1
print(count)
Output
{'Dog': 2, 'Cat': 1, 'Elephant': 1}

11.2 Find Key with Maximum Value


d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
print(max(d))
Output
e
11.3 Convert 2 lists into a Dictionary
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
Output
{'a': 1, 'b': 2, 'c': 3}

11.4 Reverse Order of Sentence


s = input("Enter your sentence - ")
def reverse(x) :
w = x.split()
w.reverse()
c = ' '.join(w)
return print(c)
reverse(s)
Output
Enter your sentence - wishing a happy birthday
birthday happy a wishing

20
11.5 Reverse A List
s = [1,2,3,4,5,6,7,8,9]
def f(x) :
x.reverse()
return print(x)
f(s)
Output
[9, 8, 7, 6, 5, 4, 3, 2, 1]

11.6 Sort a List


s = [1,2,3,4,5,6,8,7,9]
def f(x) :
x.sort()
return print(x)
f(s)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

21
12.1 Return Index of a Target 18/10/2024
s = [1,2,3,4,5]
print (s)
t = int(input("Enter desired element - "))
def find_index(l,t):
i = l.index(t)
return print("Index of desired element is ",i)
find_index(s,t)
Output
[1, 2, 3, 4, 5]
Enter desired element - 5
Index of desired element is 4

12.2 Convert String to Uppercase


s = input("Enter a sentence - ")
def string_to_upper(x):
return x.upper()
print (string_to_upper(s))
Output
Enter a sentence - hello i am chirjot
HELLO I AM CHIRJOT

12.3 Remove duplicates from a List – 18/10/2024


l = [1,2,3,3,4,2,2,1]
print (l)
def remove_duplicates(x):
return list(set(x))
print(remove_duplicates(l))
Output
[1, 2, 3, 3, 4, 2, 2, 1]
22
[1, 2, 3, 4]

12.4 Factorial of a Number


n = int(input("Enter a number - "))
def factorial(x):
m=1
t=1
for m in range(1,x+1) :
t*=m
return print(x,"! = ",t)
factorial(n)
Output
Enter a number - 5
5 ! = 120

12.5 Add ‘a’ to itself ‘b’ times


a = int(input("Enter value for 'a' - "))
b = int(input("Enter value for 'b' - "))
def sum_fun(x,y) :
if y == 0 :
return 0
else :
return x+sum_fun(x,y-1)
print (sum_fun(a,b))
Output
Enter value for 'a' - 6
Enter value for 'b' - 4
24

23
12.6 Sum of variable number of arguments
y = []
m = int(input("Enter number of arguments - "))
n=1
while n<(m+1) :
x = int(input("Enter a number - "))
y.append(x)
n+=1
print(y)
def sum_numbers(x) :
t=0
for w in x :
t+=w
return(print(t))
sum_numbers(y)
Output
Enter number of arguments - 4
Enter a number - 56
Enter a number - 45
Enter a number - 645
Enter a number - 14
[56, 45, 645, 14]
760

12.7 Return Full Name using first and last name


a = str(input("Enter your first name - "))
b = str(input("Enter your last name - "))
def greet_full_name(x,y) :
return (print("Full Name - ",x,"",y,))
greet_full_name(a,b)
24
Output
Enter your first name - Chirjot
Enter your last name - Singh
Full Name - Chirjot Singh

12.8 Area of Circle


r = int(input("Enter radius of circle - "))
def circle_area(x) :
return (print("Area of circle = ",(3.1416)*(x**2)))
circle_area(r)
Output
Enter radius of circle - 7
Area of circle = 153.9384

25
13.1 Class for SI and CI 22/10/2024
x = int(input("Enter principle amt. - "))
y = int(input("Enter rate of interest - "))
z = int(input("Enter time duration (in years) - "))
class Interest:
def si(self,p,r,t):
return((p*r*t)/100)
def ci(self,p,r,t):
return(p*((1+(r/100))**t)- p)
m = Interest()
print(m.si(x,y,z))
print(m.ci(x,y,z))
Output
Enter principle amt. - 100
Enter rate of interest - 4
Enter time duration (in years) - 5
20.0
21.66529024000002

13.2 Class for area of Rectangle


class rectangle :
def area_rect(l,b):
return print("Area = ",l*b)
obj1 = [5,3]
obj2 = [7,5]
obj3 = [3,5]
rectangle.area_rect(obj1[0],obj1[1])
rectangle.area_rect(obj2[0],obj2[1])
rectangle.area_rect(obj3[0],obj3[1])

26
Output
Area = 15
Area = 35
Area = 15

27
14.1 Identify if number is Prime 23/10/2024
n = int(input("Enter a number - "))
def check_prime(x) :
t=1
m=0
if x==0 or x==1 :
print("Neither Prime nor Composite")
elif x>0 :
while t<=n :
if x%t==0:
m+=1
t+=1
if m>2 :
print("Not Prime")
else:
print("Prime")
check_prime(n)
Output
Enter a number – 41
prime

14.2 Maximum of 3 Numbers


l = []
m = int(input("Enter 1st number - "))
l.append(m)
n = int(input("Enter 2nd number - "))
l.append(n)
o = int(input("Enter 3rd number - "))
l.append(o)
print("Maximum number is ",max(l))
28
Output
Enter 1st number - 50
Enter 2nd number - 12
Enter 3rd number - 12
Maximum number is 50
45. Area of Rectangle using Module – 05/11/2024
Module
def SqrA(a,b):
return (a*b)
Program
import Module1
l = int(input("Enter dimension of Side 1 - "))
m = int(input("Enter dimension of Side 2 - "))
print(Module1.SqrA(l,m))

29
05/11/2024
15.1 Area of Rectangle using Module
Module

def SqrA(a,b):

return (a*b)

Program

import Module1

l = int(input("Enter dimension of Side 1 - "))

m = int(input("Enter dimension of Side 2 - "))

print(Module1.SqrA(l,m))

Output

Enter dimension of Side 1 – 5


Enter dimension of Side 2 - 4
20

15.2 Record Transactions with Date


Module
def record_transaction(x,y,z):
if y == "+":
x+=z
elif y == "-":
x-=z
return(x)
Program
import Module1
b = int(input("Enter your initial balance - "))
n = int(input("Enter number of transactions - "))
l=[]
for q in range(n):
30
d = str(input("Enter date of transaction - "))
s = str(input("Enter status (+/-) - "))
a = int(input("Enter amount of transaction - "))
k = ("Date - ",d,"Total Balance - ",Module1.record_transaction(b,s,a))
l.append(k)
b=Module1.record_transaction(b,s,a)
print(l)
Output
Enter your initial balance - 1000
Enter number of transactions - 4
Enter date of transaction - 12
Enter status (+/-) - +
Enter amount of transaction - 245
Enter date of transaction - 15
Enter status (+/-) - -
Enter amount of transaction - 124
Enter date of transaction - 18
Enter status (+/-) - -
Enter amount of transaction - 32
Enter date of transaction - 25
Enter status (+/-) - +
Enter amount of transaction - 937
[('Date - ', '12', 'Total Balance - ', 1245), ('Date - ', '15', 'Total Balance - ', 1121), ('Date - ', '18', 'Total Balance - ',
1089), ('Date - ', '25', 'Total Balance - ', 2026)]

31
16. Create Class for Adding 2 Numbers 07/11/2024
class Maths :
def add(self,a,b):
return a+b
ob1 = Maths()
print(ob1.add(4,3))

Output
7

32
14/11/2024
17. Take 1D Array Argument and return 1D Array Argument containing only positive
elements of input Array
import numpy as N
x = N.arange(10)-5
print(x)
def pos_e(a):
return N.arange(4)+1
pos_x = pos_e(x)
print (pos_x)

Output
[1 2 3 4]

33
18.1 Create a bar graph in python using matplotlib 19/11/2024
import matplotlib.pyplot as plt
import numpy as ny
x=['1-10','11-20','21-30']
y=[60,70,80]
>>> plt.bar (x,y)
<BarContainer object of 3 artists>
>>> plt.title("Runs in different phases")
Text(0.5, 1.0, 'Runs in different phases')
>>> plt.xlabel("Overs")
Text(0.5, 0, 'Overs')
>>> plt.ylabel ("Runs Scored")
Text(0, 0.5, 'Runs Scored')
>>> plt.show()

Output

34
18.2 Create a line graph using matplotlib
# plot, scatter, bar, hist, xlabel, ylabel, title, legend.
import matplotlib.pyplot as plt
x=[1,2,3,4]
y=[2,4,6,8]
plt.plot(x,y)
plt.show()
Output

18.3 Create a pie chart using matplotlib


import matplotlib.pyplot as plt

slices = [50, 20, 15, 10, 5]


dept = ['Sales', 'HR', 'Finance', 'Production', 'Account']
cols = ['magenta', 'cyan', 'green', 'red', 'blue']
35
exp = [0, 0.2, 0.3, 0, 0]

plt.pie(slices, labels=dept, colors=cols, startangle=90, explode=exp, shadow=True, autopct='%.1f%%')


plt.title('KVS')
plt.legend()
plt.show()
Output

18.4 Draw a histogram using matplotlib


import matplotlib.pyplot as plt

age = [22, 32, 35, 45, 55, 14, 26, 19, 56, 44, 48, 33, 38, 38, 28]
years = [0, 10, 20, 30, 40, 50, 60]

plt.hist(age, bins=years, color='magenta', histtype='bar', rwidth=0.6)


plt.xlabel('Emp Age')
plt.ylabel('Number of Emp')
plt.title('KVS')
plt.legend()
36
plt.show()
Output

18.5 Draw a scatter plot using matplotlib


x = [25, 24, 23, 16, 29, 36, 48]
y = [4, 6, 10, 14, 9, 7, 4]

plt.scatter(x, y, color='red', marker='x')


plt.xlabel('age')
plt.ylabel('No of Employee')
plt.show()
Output

37
38
19.1Write a python program to read a csv file 22/11/2024
with open (r"C:\Users\chirjot singh\Desktop\writer.txt","r") as file:
content=file.read()
print(content)
Output

19.2 Write a python program to overwrite the content on an existing csv file
file=open(r"C:\Users\chirjot singh\Desktop\writer.txt","w")
file.write("This is a Python and Data Fundamentals class")
file.write("This is BMS-1C")
file.close()

with open (r"C:\Users\chirjot singh\Desktop\writer.txt","r") as file:


content=file.read()
print(content)
Output

19.3 Write a function COUNTAE() in python to read lines from text file WRITER.TXT,
and display those lines, which are starting either with A or starting with E.
def COUNTAE():
try:
with open(r"C:\Users\neelesh gupta\Desktop\writer.txt", "r") as file:
data = file.readlines()
for w in data:
if w.strip() and (w.strip()[0] == "A" or w.strip()[0] == "E"):
print(w.strip())
except FileNotFoundError:

39
print("The file does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
COUNTAE()
Output

40
28/11/2024
20.1 Write a python code to create a series using list and multiply each element by 2.
import pandas as pd
data=[1,2,3,4,5]
df=pd.Series(data)
print(df)
print(df*2)
Output

20.2 Write a python code to create two series using tuple and array along with assigning
index and perform basic operations.
import pandas as pd
import numpy as np
data1=np.arange(10)
data2=(10,20,30)
df1=pd.Series(data1,index=np.arange(10,20))
df2=pd.Series(data2,index=['a','b','c'])
print(df1)
print(df2)
print(df1**2)
print(df1[df1>2])
Output

41
20.3 Write a python program to create a DataFrame
import pandas as pd
data={"Name":["Amit","Joy","Bob"],"Age":[26,24,25],"City":["Delhi","Mumbai","Kolkata"]}
df=pd.DataFrame(data)
print(df)
Output

20.4 Write a python code to load the data from diabetes.csv file into a pandas DataFrame.
import pandas as pd
df2=pd.read_csv("C:/Users/neelesh gupta/Downloads/csv file.csv")
print(df2)

42
Output

20.5 Write a python program to create two dataframes and combine them
import pandas as pd
dict1={'id':['1','2','3','4','5'],'value1':['A','C','E','G','I'],'value2':['B','D','F','H','J']}
dict2={'id':['2','3','6','7','8'],'value1':['N','M','O','Q','S'],'value2':['L','N','P','R','T']}
df1=pd.DataFrame(dict1)
df2=pd.DataFrame(dict2)
df3=pd.concat([df1,df2])
print(df3)
Output

43
20.6 Write a python program to create two data frames and combine them in different
data sets using merge.
import pandas as pd
dict1={'id':['1','2','3','4','5'],'value1':['A','C','E','G','I'],'value2':['B','D','F','H','J']}
dict2={'id':['2','3','6','7','8'],'value1':['N','M','O','Q','S'],'value2':['L','N','P','R','T']}
df1=pd.DataFrame(dict1)
df2=pd.DataFrame(dict2)
merge={'Data1':df1,'Data2':df2}
df4=pd.concat(merge)
print(df4)
Output

20.7 Write a python code to combine the common rows between two or three dataframes
using ignore_index and merge.
import pandas as pd
dict1={'id': ['1', '2', '3', '4', '5'], 'value1': ['A', 'C', 'E', 'G', 'I'], 'value2': ['B', 'D', 'F', 'H', 'J']}
dict2={'id': ['2', '3', '6', '7', '8'], 'value1': ['N', 'M', 'O', 'Q', 'S'], 'value2': ['L', 'N', 'P', 'R', 'T']}
dict3={'id': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'], 'value3': ['12', '13', '14', '15', '16', '17', '15', '12', '13', '23',
'24']}
df1=pd.DataFrame(dict1)
df2=pd.DataFrame(dict2)
df3=pd.DataFrame(dict3)
df4=pd.concat([df1, df2], ignore_index=True)

44
df5=pd.merge(df4, df3, on='id')
print(df5)
Output

20.8 Write a python code to show the implementation of outer and inner join the two
Dataframes in pandas
import pandas as pd
dict1={'id': ['1', '2', '3', '4', '5'], 'value1': ['A', 'C', 'E', 'G', 'I'], 'value2': ['B', 'D', 'F', 'H', 'J']}
dict2={'id': ['2', '3', '6', '7', '8'], 'value1': ['N', 'M', 'O', 'Q', 'S'], 'value2': ['L', 'N', 'P', 'R', 'T']}
df1=pd.DataFrame(dict1)
df2=pd.DataFrame(dict2)
df3=pd.merge(df1,df2,on='id',how='outer')
print(df3)
df4=pd.merge(df1,df2,on='id',how='inner')
print(df4)
Output

45
20.9 Write a python program to rename the columns of dataframes while merging them
using outer join.
import pandas as pd
dict1={'id': ['1', '2', '3', '4', '5'], 'value1': ['A', 'C', 'E', 'G', 'I'], 'value2': ['B', 'D', 'F', 'H', 'J']}
dict2={'id': ['2', '3', '6', '7', '8'], 'value1': ['N', 'M', 'O', 'Q', 'S'], 'value2': ['L', 'N', 'P', 'R', 'T']}
df1=pd.DataFrame(dict1)
df2=pd.DataFrame(dict2)
df3=pd.merge(df1,df2,on='id',how='outer',suffixes=('_left','_right'))
print(df3)
Output

20.10 Write a python code to show the implementation of left and right join the two
Dataframes in pandas.
import pandas as pd
dict1={'id': ['1', '2', '3', '4', '5'], 'value1': ['A', 'C', 'E', 'G', 'I'], 'value2': ['B', 'D', 'F', 'H', 'J']}
dict2={'id': ['2', '3', '6', '7', '8'], 'value1': ['N', 'M', 'O', 'Q', 'S'], 'value2': ['L', 'N', 'P', 'R', 'T']}
df1=pd.DataFrame(dict1)
df2=pd.DataFrame(dict2)
df3=pd.merge(df1,df2,on='id',how='right')
print(df3)
df4=pd.merge(df1,df2,on='id',how='left')
print(df4)

46
Output

47
5/12/2024
21 : You are provided with a dataset called sales_data.csv containing monthly sales data of
a company across different regions. Write a python code to perform the following tasks:-
1. Load the dataset using pandas and display the first five rows.
2. Calculate the total sales for each region.
3. Plot a bar chart to visualize the total sales per region.
4. Find the month with the highest total sales and the corresponding amount.
5. Create a line plot showing monthly sales trends for each region

import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv(r"C:\Users\neelesh gupta\OneDrive\Tài liệu\Python Sales 2.csv")
print(df.head())
N=0
S=0
W=0
E=0
for i in range(len(df)):
if df.at[i, "Region"]=="North":
N+=df.at[i,"Sales"]
elif df.at[i,"Region"]=="South":
S+=df.at[i,"Sales"]
elif df.at[i,"Region"]=="East":
E+=df.at[i,"Sales"]
elif df.at[i,"Region"]=="West":
W+=df.at[i,"Sales"]

print("Total sales of the North region is:",N)


print("Total sales of the South region is:",S)

48
print("Total sales of the East region is:",E)
print("Total sales of the West region is:",W)

Region=['East','West','North','South']
Sales=[E,W,N,S]
plt.bar(Region,Sales,color='r')
plt.xlabel('Region')
plt.ylabel('Sales')
plt.show()

for j in range(len(df)):
if df.at[j,"Sales"]==max(df["Sales"]):
print("maximim sales in",df.iat[j,0],"is",max(df["Sales"]))
grouped_data = df.groupby(['Region','Month '])['Sales'].sum().reset_index()
pivot_data = grouped_data.pivot(index='Month ', columns='Region', values='Sales')

pivot_data.plot(kind='line', marker='o', colormap='viridis')


plt.title("Monthly Sales Trends by Region")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend(title="Region")
plt.grid(True)
plt.show()
Output

49
50
19/12/2024
22.1 Palindrome Checker with a Twist
Write a Python program that does the following:
1. Take a sentence as input from the user.
2. Remove all spaces, punctuation, and special characters from the sentence.
3. Convert all characters to lowercase.
4. Check if the processed string is a palindrome (reads the same backward as forward).
5. Display an appropriate message indicating whether or not the input sentence is a palindrome.

import re
s=input("Enter the sentence:")
def remove_special_characters(string):
return re.sub(r'[^a-zA-Z0-9]', '', string)

s1=remove_special_characters(s)
print(s1)
s2=s1.lower()
print(s2)
s3=list(s2)
print(s3)
s4 = s3[::-1] # Create a reversed version of s3
if s3 == s4:
print("It is Palindrome")
else:
print("It is not Palindrome")
Output
Enter the sentence: hello mister ?? how are you!!
hellomisterhowareyou
hellomisterhowareyou

51
['h', 'e', 'l', 'l', 'o', 'm', 'i', 's', 't', 'e', 'r', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u']
It is not Palindrome

22.2 Find Prime Numbers in a Range


Write a Python program to:
1. Take two numbers, start and end, as input.
2. Print all the prime numbers between start and end (inclusive)

a = int(input("Enter the lower limit: "))


b = int(input("Enter the upper limit: "))

lst = []

# Loop through the range


for i in range(a, b + 1):
if i > 1: # Prime numbers are greater than 1
for j in range(2, int(i**0.5) + 1): # Check divisors up to the square root of i
if i % j == 0:
break
else: # Executed if the loop is not broken, meaning i is prime
lst.append(i)

print(lst)

Output
Enter the lower limit:10
Enter the upper limit:30
[11, 13, 17, 19, 23, 29]

52

You might also like