List of Practicals Python 2024 - 25
List of Practicals Python 2024 - 25
import pandas as pd
dic = {'A':45,'B':55,'C':67,'D':78}
print("*****Dictionary Object********")
print(dic)
print("****Series object is created from Dictionary*****")
s = pd.Series(dic)
print("*****Series Object*****")
print(s)
import pandas as pd
import numpy as np
print("**** ND-Array ****")
nd = np.arange(1,10)
print(nd)
print("****Series object****")
s = pd.Series(nd)
print(s)
print("***Series object is created from nd-array***")
Opuput---
2. Create a series "S1" showing charity contribution made by each section of grade 12.
import pandas as pd
sec=['A','B','C','D']
contri=[1450,1550,1750,1650]
s1=pd.Series(data = contri,index=sec)
print(s1)
Output---
3. Write Python program to Create a DataFrame with the help of dictionary, which
contains theinformation about Marks of Five students of five subjects.
import pandas as pd
studMark ={'Name': ["Ram","Aman","Akash","Ramesh","Virat"],
'Maths':[85,95,88,99,80],
'Sc' :[95,100,99,88,75],
'Ssc':[80,100,99,99,85],
'Hindi':[70,99,99,98,90],
'English':[80,70,90,90,95],
'Total':[410,464,475,474,425]}
students = pd.DataFrame(studMark)
print(students)
Output ---
4.Write a program to create a dataframe players using a list of names and scores of the previous three
matches.
import pandas as pd
data = [["Virat",55,66,31],["Rohit",88,66,43],["Samson",99,101,68]]
players = pd.DataFrame(data, columns = ["Name","Match-1","Match-2","Match-3"])
print(players)
Output---
5.Create a data frame for examination results and display row labels, column labels data types of each
column and the dimensions.
import pandas as pd
res={'Amit':[76,78,75,66,68],
'Shialesh':[78,56,77,49,55],
'Rani':[90,91,93,97,99],
'Madan':[55,48,59,60,66],
'Radhika':[78,79,85,88,86]}
df=pd.DataFrame(res)
print("Prinitng row labels in a list:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
idx=df.index
l=list(idx)
print(l)
print("Prinitng row labels in a list:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("[",end=" ")
for col in df.columns:
print(col,end=" ")
print("]")
print("Printing Data Types of each column")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.dtypes)
print("Printing dimensions of Data Frame")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.ndim)
Output---
6. Create the following DataFrame Sales containing year wise sales figures for five salespersons in INR.
Use the years as column labels, and salesperson names as row labels.
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
#Display row lables
print("Row Lables:\n",sales.index)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display column lables
print("Column Lables:\n",sales.columns)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display data type
print("\nDisplay column data types")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.dtypes)
print("\nDisplay the dimensions, shape, size and values of Sales")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Dimensions:",sales.ndim)
print("Shape:",sales.shape)
print("Size:",sales.size)
print("Values:",sales.values)
Output---
7.Create the following DataFrame Sales containing year wise sales figures for five salespersons in INR.
Use the years as column labels, and salesperson names as row labels.
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
Sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Display last two rows of DataFrame:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(Sales.tail(2))
print()
print("Display first two columns of Dataframe:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(Sales[[2018,2019]])
Output---
8.Create the following DataFrame Sales containing year wise sales figures for five salespersons in INR.
Use the years as column labels, and salesperson names as row labels.
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Transpose:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.T)
print("\nSales made by each salesman in 2018")
print(sales[2018])
print("Sales made by Kapil and Mohini:")
print(sales.loc[['Kapil','Mohini'], [2019,2020]])
print("Add Data:")
sales.loc["Nirali"]=[221, 178, 165, 177]
print(sales)
print("Delete Data for 2018:")
sales.drop(columns=2018,inplace=True)
print(sales)
sales=sales.drop("Shikhar",axis=0)
print(sales)
sales=sales.rename({"Kamini":"Rani","Kapil":"Anil"},axis="index")
print(sales)
sales.loc[sales.index=="Mohini",2018]=150
print(sales)
Output---
9. Plot the following data on a line chart and customize the chart according to the below-given
instructions:
Output---
10. Pratyush Garments has recorded the following data into their register for their income from cotton
clothes and jeans. Plot them on the line chart.
import matplotlib.pyplot as pp
day =['Monday','Tuesday','Wednesday','Thursday','Friday']
ct = [450,560,400,605,580]
js = [490,600,425,610,625]
pp.plot(day,ct,label='Cotton',color='g',linestyle='dotted',marker='+')
pp.plot(day,js,label='Food',color='m',linestyle='dashdot',marker='x')
pp.title("The Weekly Garment Orders")
pp.xlabel("Days")
pp.ylabel("Orders")
pp.legend()
pp.show()
Output---
11. Write a program to create a dataframe salesman using the series sales_person which stored saleman
names and quantity of sales of August.
import pandas as pd
sales_person = [["Ram",55],["Ajay",22],["Vijay",67],["Sachin",44]]
salesman = pd.DataFrame(sales_person,columns=["Name","Sales(August)"])
print(salesman)
Output---
Print the batsman name along with runs scored in Test and T20 using column names and dot notation.
import pandas as pd
# Creating the Data
player_data = {"Name":["Virat Kohli","Ajinkya Rahane","Rohit Sharma","Shikhar
Dhawan","Hardik Pandya"],
"Test" : [3543,2578,2280,2158,1879],
"ODI" : [2245,2165,2080,1957,1856],
"T20" : [1925,1853,1522,1020,980]
}
data = pd.DataFrame(player_data)
# The following line is used to start the index from 1
data.index = data.index + 1
# ---------------------
print(data.Name)
print(data.Test)
print(data.T20)
Output---
Display the Batsman name along with runs scored in ODI using loc.
import pandas as pd
data = pd.DataFrame(player_data)
# The following line is used to start the index from 1
data.index = data.index + 1
# ---------------------
print(data.loc[:,('Name','ODI')])
Output---
14. Consider following data and write a program to do the following:
import pandas as pd
data = pd.DataFrame(player_data)
# The following line is used to start the index from 1
data.index = data.index + 1
# =======================
print(data[data.columns[0]])
print(data[data.columns[2]])
Output---
Reindex the dataframe created above with batsman name and delete data of Hardik Pandya and Shikhar
Dhawan by their index from original dataframe.
import pandas as pd
# Creating the Data
player_data = {"Name":["Virat Kohli","Ajinkya Rahane","Rohit Sharma","Shikhar
Dhawan","Hardik Pandya"],
"Test" : [3543,2578,2280,2158,1879],
"ODI" : [2245,2165,2080,1957,1856],
"T20" : [1925,1853,1522,1020,980]
}
data = pd.DataFrame(player_data)
# The following line is used to start the index from 1
data.index = data.index + 1
# ----------------------
data = data.set_index('Name')
print(data)
# Now deleting records
print("Records after Deleting the values:")
data = data.drop(['Shikhar Dhawan','Hardik Pandya'])
print(data)
Output---
16. School celebrated volunteering week where each section of class XI dedicated a day for
collecting amount for charity being supported by the school. Section A volunteered on
Monday, B on Tuesday, C on Wednesday and so on. There are six sections in Class XI.
Amounts collected bysections A to F are 8000, 12000, 9800, 11200, 15500, 7300.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
S=['A','B','C','D','E','F']
A=[8000,12000,9800,11200,15500,7300]
plt.bar(S,A)
plt.xlabel('Sections')
plt.bar(S,A)
plt.xlabel('Section')
plt.ylabel('Amount Collected')
plt.show()
Output---
17. Dhriti wants to plot a line chart based on the given data to view the changing weekly average temperature
for four weeks. Help her to write the code in Python. Also give appropriate chart title and axis titles.
import matplotlib.pyplot as plt
Week=[1, 2, 3, 4]
Temp =[30, 34, 28, 32]
plt.plot(Week, Temp)
plt.title("Change in Temperature Weekly")
plt.xlabel("Week")
plt.ylabel("Temperature")
plt.xticks(Week)
plt.show()
18.Write python code to plot bar chart for Class wise result analysis as shown below.
Give appropriate Chart title and axes labels
Class VI VII VIII IX X XI
Average_Percentage 70 75 65 80 78 68
import matplotlib.pyplot as plt
classes = ["VI", "VII", "VIII", "IX", "X", "XI"]
average_percentage = [70, 75, 65, 80, 78, 68]
plt.bar(classes, average_percentage)
plt.title("Class wise Result Analysis-Average Percentage")
plt.xlabel("Student Class")
plt.ylabel("Average Percentage")
plt.show()
19.Parth is a student of class XII. He wants to represent the following data in the bar chart with
label “Fruit Name” on X-axis and “Monthly Expenditure” on Y-axis. He wants that edge color
of the bar should be “red”. Help him to write the code.
Fruits Monthly Expenditure(Rs)
Banana 300
Apple 600
Grapes 500
Papaya 740
Melon 450
20.Write python code to plot a bar chart shown below. Colour of each bar is given below:
)
Expenditure")plt.show(
Name")plt.ylabel("Monthly
Fruits")plt.xlabel("Fruit
on
Expenditure
edgecolor="red")plt.title("Monthly
cost,
450]plt.bar(fruit,
740,
500,
600,
[300,
=
"Melon"]cost
"Papaya",
"Grapes",
"Apple",
["Banana",
=
pltfruit
as
matplotlib.pyplot
Yellowimport
–
GreenPunjab
–
CyanGujarat
–
MagentaKerala
–
BlackAP
–
below:UP
given
is
bar
each
of
Colour
below.
shown
chart
bar
a
plot
to
code
python
19.Write
UP – Black
AP – Magenta
Kerala – Cyan
Gujarat – Green
Punjab – Yellow