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

12th Practical

The document discusses various practical exercises related to Python data analysis using Pandas library. It includes creating and modifying Series and DataFrame objects, performing operations like statistics, indexing and slicing. It also discusses creating basic visualizations like histograms, pie charts and bar plots using Matplotlib.

Uploaded by

Anjana
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)
71 views

12th Practical

The document discusses various practical exercises related to Python data analysis using Pandas library. It includes creating and modifying Series and DataFrame objects, performing operations like statistics, indexing and slicing. It also discusses creating basic visualizations like histograms, pie charts and bar plots using Matplotlib.

Uploaded by

Anjana
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
You are on page 1/ 21

Informatics Practices

(2024 – 2025)

Code No. 065

Index
S.No Name of the Practical Remarks
Based on Series
1. Series creation using python sequence
2. Series creation using dictionary
3. Modify series data
4. Accessing series data
5. Perform head and tail function
6. Using attributes of series object
Based on DataFrame
7. Create DataFrame from list conating
dictionary
8. Accessing DataFrame object
9. Append data to DataFrame
10. Perform statistics funtion on DataFrame
Based on Matplotlib
11. Construct a Histogram
12. Construct a circular pie chart
13. Create a horizontal bar chart
14. Draw a line chart
15. Create a bar chart
Based on MySql
16. Create table product
17. Insert data into product table
18. Retrieve data from product table
19. Add new column to product table
20. Update product table
21. Increase price by update table
22. Perform group operation on table
23. Perform sql function
24. Aliases in query
25. Aliases based join

Practical Based On Series


Practical No 1.

Problem Statement : Create a Series Object using the python sequence with 5 elements.

Solution

Source Code
import pandas as pd

L= [12,23,34,45,56]
S = pd.Series(L)
print(S)

Output :

Practical No 2
Problem Statement : Write a program to create a Series Object using a dictionary that stores
the number of students in each section of class 12 in your school.
Solution
Source Code

import pandas as pd
stu = {'A': 39 ,'B' :41, 'C':42, 'D' :44}
ser = pd.Series(stu)
print(ser)

Output :

Practical No 3
Problem Statement : Consider the Series object s13 that stores the contribution of each
section, as shown below:

A 6700
B 5600
C 5000
D 5200

Write a code to modify the amount of section 'A' as 7600 and for section 'C' and 'D' as 7000.
Print the changed object.
Solution

Source Code

import pandas as pd
data = {'A': 6700 ,'B' :5600 , 'C':5000, 'D' :5200}
s13= pd.Series(data)
s13[0] = 7600
s13[2:]=7000
print("Seires Object after modifying amounts : ")
print(s13)

Output:

Practical No 4
Problem Statement : A Series Object s11 stores the charity contribution made by each section (see
below):

A 6700
B 5600
C 5000
D 5200
Write a program to display which section made a contribution more than 5500/-
Solution
Source Code:

import pandas as pd
sec=['A','B','C','D']
amount = [6700,5600,5000,5200]
s11 = pd.Series(amount,index=sec)
print("Contribution > 5500 by : ")
print(s11[s11>5500])

Output :

Practical No 5
Problem Statement : Create a Series 'temp' that stores temperature of seven days in it. Its index
should be 'Sunday', 'Monday'.....
Write Script to
1. Display temp of first 3 days.
2. Display temp of last 3 days.
3. Display all temperature in reverse order like saturday, friday and so on.
4. Display temperature from tuesday to friday.
5. Display square of all temperature.
Solution
Source Code
import pandas as pd
temp = pd.Series([45,42,40,46,39,38,40], ['Sunday','Monday','Tuesday',
'Wednesday','Thursday','Friday','Saturday'])
print(temp,"\n")
print("Temp of first three days \n ",temp.head(3) ,"\n")
print("Temp of last three days \n ",temp.tail(3) ,"\n")
print("Temp in reverse order \n ", temp[: :-1] ,"\n")
print("Temp from tuesday to friday \n", temp['Tuesday' : 'Friday'] ,"\n")
print("Square of all temperature \n " ,temp *temp)

Output :
Practical No 6
Problem Statement : – Create a Series Object 'employee' that stores salary of 7 employees.

Write script to print


• Total no. Of employee.
• Series is empty or not
• Series consist NAN value or not
• Count non – NAN elements
• Axis labels
Solution:
Practical Based On DataFrame
Source Code

import pandas as pd

dict1 = { 'Raman' : 34000 ,'Priyansh' : 42000 ,'Rajesh' :23000 ,'Suman' : 45000 ,'Manya' : 30000 }
employee = pd.Series(dict1)
print(employee)
print("Total no of employees : ",employee.size)
if employee.empty :
print("Series is empty " )
else :
print("Series is not empty")
if employee.hasnans :
print("Series contain NAN elements")
else :
print("Series not contain NAN elements")
print("Total no of elements",employee.count())
print("Axis Labels \n",employee.index)

Output

Practical No 7
Problem Statement : Create a dataframe from list containing dictionaries of most economicalbike
with its name & rate of three companies.
Solution :
Source Code
import pandas as pd

L1 = {'Name' : 'Sports','Cost' : 80000}


L2 = {'Name' : 'Discover','Cost' : 83000}
L3 = {'Name' : 'Splendor','Cost' : 85000}
bike = [L1,L2,L3]
df = pd.DataFrame(bike,['TVS','Bajaj','Hero'])
print(df)
Output:

Practical No 8
Problem Statement : Create the following DataFrame Sales containing year wise sales figure for
five salespersons in INR.Use the years as a column lables and salespersons names as a row labels.

Now perform the following operation on it:


(a) Display the row lables of Sales. (b) Display the column lables of Sales.
(c) Display the datatype of each Sale. (d) Display the last two rows of Sale.
(e) Display the first two columns of Sales.

Solution
Source Code
D = { 2014 : [1000,1500,2000,3000,4000], 2015 : [2000,1800,2200,3000,4500],
2016 : [2400,5000,7000,1000,1250], 2017 : [2800,6000,3000,7000,8000] }

Sales = pd.DataFrame(D,['Madhu', 'Kusum', 'Ankit', 'Shruti', 'Krishna'])


print(" ------------- DataFrame Sales ------------ ")
print(Sales)
print("\n(a) Row Labels of Sales :",Sales.index)
print("\n(b) Column Labels of Sales :",Sales.columns)
print("\n(c)DataType of each column : \n",Sales.dtypes,"\n")
print("\n(d)Last two rows of Sales \n",Sales.iloc[3:,],"\n")
print("(e)First two columns of Sales \n",Sales.iloc[:,:2])
Output:

Practical No 9
Problem Statement : Create a DataFrame 'Sales 2 ' using dictionary as given below and write a
program to append 'Sales 2' to the dataframe 'sales' created in practical no. 9.

2018
Madhu 1000
Kusum 1100
Ankit 5000
Shruti 3400
Krishna 9000

Solution
Source Code
D = { 2014 : [1000,1500,2000,3000,4000], 2015 : [2000,1800,2200,3000,4500],
2016 : [2400,5000,7000,1000,1250], 2017 : [2800,6000,3000,7000,8000] }

Sales = pd.DataFrame(D,['Madhu', 'Kusum', 'Ankit', 'Shruti', 'Krishna'])


print(" ------------- DataFrame Sales ------------ ")
print(Sales)
Sale2 = pd.DataFrame({2018 : [1600,1100,5000,5400,9000] },
['Madhu', 'Kusum', 'Ankit', 'Shruti', 'Krishna'])

print(" ------------- DataFrame Sale2 ------------ ")


print(Sale2)
Sales = Sales.join(Sale2)
print(" --------- Append Sale2 to Sales ----------")
print(Sales)
print(Sale)

Output :

Practical No 10
Problem Statement : Create a data frame df1 as shown below:

(i) Write command to compute sum of every column of the dataframe.


(ii) Write command to compute mean of column Rainfall.
(iii)Write command to compute Median of the MaxTemp Column.

Solution :
Source Code:
dict1 = {'City' : ['Delhi','Bengaluru','Chennai','Mumbai','Kolkata'],
'MaxTemp' : [40,31,35,29,39],"MinTemp" : [32,25,27,21,23],
'RainFall' : [24.1,36.2,40.8,35.2,41.8]}

df1 = pd.DataFrame(dict1)
Practical Based On Matplotlib
print(df1)
print("\nSum of every column : \n",df1.sum())
print("\nMean of column Rainfall : \n", df1['RainFall'].mean())
print("\nMedian of the MaxTemp Column :",df1.loc[:,'MaxTemp'].median())

Output:

Practical No 11
Problem Statement : The Following Seat booking are the daily rewards of a month December
from PVR Cinemas:
124,124,135,156,128,189,200,150,158,150,200,124,143,142,130,130,170,189,200,130,142,167,180
,143,143,135,156,150,200,189,142
Consturct a histogram from above data.

Solution :
Source Code

import pandas as pd
import matplotlib.pyplot as plt
L = [124,124,135,156,128,189,200,150,158,
150,200,124,143,142,130,130,170,
189,200,130,142,167,180,143,143,
135,156,150,200,189,142]
plt.hist(L)
plt.title("Booking Records @ PVR")
plt.show()

Output :

Practical No 12
Problem Statement : In an engineering college, number of admission stream wise in the current
year are :
Civil = 15, Electrical = 35, Mechnical = 40, Chemical = 20, CS = 50
Write a program to print information on a circular pie chart, creating a wedge for CS stream.
Solution :
Source Code:

import matplotlib.pyplot as plt


stream = ['Civil','Electrical','Mechanical','Chemical','CS']
adm = [15,35,40,20,50]
plt.title("Admission StreamWise")
plt.axis("equal")
expl = [0,0,0,0,0.2]
plt.pie(adm, labels = stream, explode= expl, autopct="%5.1f%%")
plt.show()

Output:
Practical No 13
Problem Statement : Write a program to create a horizontal bar chart from two data sequence as
given below :
means = [20,35,30,35,27]
stds = [2,3,4,1,2]
Make sure to show legends.
Solution:
Source Code
import matplotlib.pyplot as plt
import numpy as np
means = [20,35,30,35,27]
stds = [2 ,3 ,4, 1 ,2]
indx = np.arange(len(means))
plt.barh(indx, means, color = 'cyan' ,label='means')
plt.barh(indx+0.25, stds, color='olive', label = 'stds')
plt.legend()
plt.show()
Output:

Practical No 14
Problem Statement : Write a Python program to draw line charts from the given financial data of
ABC Co. For 5 days in the form a DataFrame namely fdf as shown below:
Solution
Source Code
import matplotlib.pyplot as plt
import pandas as pd
dict1 = {'Day1' : [74.25,76.06,69.50,72.55],
'Day2' : [56.03,68.71,62.89,56.42],
'Day3' : [59.30,72.07,77.65,66.46],
'Day4' : [69.00,78.47,65.53,76.85],
'Day5' : [89.65,79.65,80.75,85.08]}

fdf = pd.DataFrame(dict1)
plt.plot(fdf)
plt.legend(["Day1","Day2","Day3","Day4","Day5"], loc="lower center")
plt.show()

Output:

Practical No 15
Problem Statement : KDPS school celebrated volunteering week where each section of class XI
dedicated a day for collecting amout 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.Amount collected by section A to F are 8000,12000,9800,11200,15500,7300.

Write a program to create a bar chart showing collection amount.The graph should have proper title
and axes titles.
Solution :
Source Code
import matplotlib.pyplot as plt
import numpy as np
Col = [8000,12000,9800,11200,15500,7300]
Practical Based On MySql
X = np.arange(6) # range to signify 6 days
plt.title("Volunteering week Collection")
plt.bar(X,Col,color='r', width = 0.25)
plt.xlabel("Days")
plt.ylabel("Collection")
plt.show()

Output:

From Practical No 16
Problem Statement : Consider the following table structure named “ Product “ showing details of
products being sold in a grocery shop.
Column Name Description DataType
P_Code Unique code of product char
P_Name Product Name varchar
P_Price Price of the Product float
Manufacturer Company name varchar
Create the table Product with appropriate data types and constraints

Solution:
Query
Create table Product
-> (
-> P_Code char(4) primary key,
-> P_Name varchar(30) not null,
-> P_Price float,
-> Manufacturer varchar(30)
-> );

Output:

Practical No 17
Problem Statement : From the above created table list insert the follwing 5 records.

P_Code P_Name P_Price Manufacturer


P01 Washing Powder 120 Surf
P02 ToothPaste 54 Colgate
P03 Soap 25 Lux
P04 ToothPaste 65 Pepsodant
P05 Soap 38 Dove
P06 Shampoo 245 Dove
Solution:
Query
mysql> insert into product values('P01','WashingPowder',120,'Surf');

mysql> insert into product values('P02','ToothPaste',54,'Colgate');

mysql> insert into product values('P03','Soap',25,'Lux');

mysql> insert into product values('P04','ToothPaste',65,'Pepsodant');

mysql> insert into product values('P05','Soap',38,'Dove');

mysql> insert into product values('P06','Shampoo',245,'Dove');

Output:
Practical No 18
Problem Statement : List the Product Code, Product name and Product Price in ascending order
of their Product Name.
Solution:
Query
mysql> Select P_Code,P_Name,P_Price from product order by P_Name ;
Output :

Practical No 19
Problem Statement : Add a new column Discount to the table Product.
Solution:
Query
mysql> ALTER TABLE Product ADD COLUMN Discount Float;
Output:
Practical No 20
Problem Statement : Calculate the value of the discount in the Product table as 10 percent of the
P_Price for all those products where the P_Price is more than 100, otherwise the discount will be 0.
Solution:
Query :
mysql> UPDATE Product
-> SET Discount = 0.10*P_Price
-> WHERE P_Price>100;
Output :

Now table product will look like this

Practical No 21
Problem Statement : Increase the price by 12 percent for all the product manufactured by Dove.
Solution
Query:
mysql> UPDATE Product
-> SET P_Price = P_Price + P_Price * 0.12
-> WHERE Manufacturer = 'Dove';
Output :

Now table will be look like this


Practical No 22
Problem Statement : Display the total number of products manufactured by each manufacturer.

Solution:
Query

mysql> select manufacturer, count(P_Code) from product


-> group by manufacturer;
Output :

Practical No 23
Problem Statement : Write the following queries using Mysql Function.
1. To remove leading spaces of string ' RDBMS MySQL'.
2. Covert and display string 'Large' into uppercase.
3. Display the result of 32
4. Round off value 15.193 to nearest ten's.
5. To display current date on your system.
Solution
Query

mysql> select ltrim(' RDBMS MySql');

mysql> select upper('Large')"Uppercase";

mysql> select power(3,2)"Raised";

mysql> select round(15.193,-1)"Round";

mysql> select curdate();


Practical No 24
Problem Statement : Consider the following two tables in database:

Write a query to display Item_Code, Item_Name and corresponding Brand_Name of those Items,
whose Price is between 20000 and 40000 (both values inclusive)
Solution:
Query
mysql> Select I.Item_Code, Item_Name,Brand_Name
-> from Item I, Brand B
-> where I.Item_Code = B.Item_Code
-> and Price between 20000 and 40000;

Output:
Practical No 25
Problem Statement : By using the table from Practical 24 display Item_Code, Price and
Brand_Name of the item, which has Item_Name as “Computer”.
Solution:
Query:

mysql> Select I.Item_Code, Price,Brand_Name


-> from Item I,Brand B
-> where I.Item_Code = B.Item_Code
-> and Item_Name = "Computer";
Output:

Completed

You might also like