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

List of Practicals Python 2024 - 25

Uploaded by

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

List of Practicals Python 2024 - 25

Uploaded by

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

List of Practicals

1. Write a program to create Pandas series from dictionary and nd array.

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.

2018 2019 2020 2021


Kapil 110 205 177 189
Kamini 130 165 175 190
Shikhar 115 206 157 179
Mohini 118 198 183 169

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.

2018 2019 2020 2021


Kapil 110 205 177 189
Kamini 130 165 175 190
Shikhar 115 206 157 179
Mohini 118 198 183 169

and write code to do the following:


i) Display the last two rows of Sales.
ii) Display the first two columns of Sales.

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.

2018 2019 2020 2021


Kapil 110 205 177 189
Kamini 130 165 175 190
Shikhar 115 206 157 179
Mohini 118 198 183 169

and write code to do the following:


I. Change the DataFrame Sales such that it becomes its transpose.
II. Display the sales made by all sales persons in the year 2018.
III. Display the sales made by Kapil and Mohini in the year 2019 and 2020.
IV. Add data to Sales for salesman Nirali where the sales made are
[221, 178, 165, 177, 210] in the years [2018, 2019, 2020, 2021] respectively
V. Delete the data for the year 2018 from the DataFrame Sales.
VI. Delete the data for sales man Shikhar from the DataFrame Sales.
VII. Change the name of the salesperson Kamini to Rani and Kapil to Anil.
VIII. Update the sale made by Mohini in 118 to 150 in 2018.

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:

Month January February March April May


Sales 510 350 475 580 600

I. Write a title for the chart “The Monthly Sales Report“


II. Write the appropriate titles of both the axes
III. Write code to Display legends
IV. Display blue color for the line
V. Use the line style – dashed
VI. Display diamond style markers on data points
import matplotlib.pyplot as pp
mon =['January','February','March','April','May']
sales = [510,350,475,580,600]
pp.plot(mon,sales,label='Sales',color='b',linestyle='dashed',marker='D')
pp.title("The Monthly Sales Report")
pp.xlabel("Months")
pp.ylabel("Sales")
pp.legend()
pp.show()

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.

Day Monday Tuesday Wednesday Thursday Friday


Cotton 450 560 400 605 580
Jeans 490 600 425 610 625

Apply following customization to the line chart.


a. Write a title for the chart “The Weekly Garment Orders”.
b. Write the appropriate titles of both the axes.
c. Write code to Display legends.
d. Display your choice of colors for both the lines cotton and jeans.
e. Use the line style – dotted for cotton and dashdot for jeans.
f. Display plus markers on cotton and x markers of jeans.

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---

12. Consider following data and write a program to do the following:

SNO Batsman Test ODI T20


1 Virat Kohli 3543 2245 1925
2 Ajinkya Rehane 2578 2165 1853
3 Rohit Sharma 2280 2080 1522
4 Shikhar Dhawan 2158 1957 1020
5 Hardik Pandya 1879 1856 980

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---

13. Consider following data and write a program to do the following:

SNO Batsman Test ODI T20


1 Virat Kohli 3543 2245 1925
2 Ajinkya Rehane 2578 2165 1853
3 Rohit Sharma 2280 2080 1522
4 Shikhar Dhawan 2158 1957 1020
5 Hardik Pandya 1879 1856 980

Display the Batsman name along with runs scored in ODI using loc.

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.loc[:,('Name','ODI')])

Output---
14. Consider following data and write a program to do the following:

SNO Batsman Test ODI T20


1 Virat Kohli 3543 2245 1925
2 Ajinkya Rehane 2578 2165 1853
3 Rohit Sharma 2280 2080 1522
4 Shikhar Dhawan 2158 1957 1020
5 Hardik Pandya 1879 1856 980
Display the columns using column index number like 0, 2, 4.

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[data.columns[0]])
print(data[data.columns[2]])

Output---

15.Consider following data and write a program to do the following:

SNO Batsman Test ODI T20


1 Virat Kohli 3543 2245 1925
2 Ajinkya Rehane 2578 2165 1853
3 Rohit Sharma 2280 2080 1522
4 Shikhar Dhawan 2158 1957 1020
5 Hardik Pandya 1879 1856 980

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

import matplotlib.pyplot as plt


fruit = ["Banana", "Apple", "Grapes", "Papaya", "Melon"]
cost = [300, 600, 500, 740, 450]
plt.bar(fruit, cost, edgecolor="red")
plt.title("Monthly Expenditure on Fruits")
plt.xlabel("Fruit Name")
plt.ylabel("Monthly Expenditure")
plt.show( )

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

import matplotlib.pyplot as plt


state = ["UP", "AP", "Kerala", "Gujarat", "Punjab"]
wickets = [12, 22, 18, 15, 8]
plt.bar(state, wickets, color=['k', 'm', 'c', 'g', 'y'])
plt.title("Ranji Trophy")
plt.xlabel("State-Teams")
plt.ylabel("Wickets")
plt.yticks(wickets)
plt.show()

You might also like