You are on page 1of 26

ST.

TERESA'S SCHOOL
SESSION:-2022-23
INFORMATICS PRACTICES
SUB. CODE - 065

PRACTICAL FILE
CERTIFICATE

This is to certify that ,


Roll No:________________________of Class:XII,
Session :2022-23

has prepared the Practical file as per the


prescribed Practical Syllabus of Board

INFORMATICS PRACTICES (065)


Class XII (C.B.S.E.)

under my supervision, I am completely


satisfied by the performance.
I wish him/her all the success in life.

Principal’s Subject Teacher’s


Signature Signature

External’s Signature
Program1

Aim: Create Pandas series from dictionary of values and ndarray.

Code: Pandas series from dictionary of values

Output: Note write these outputs on left side white paper of your register. Use Pencil Colors in
bar chart, Line chart etc. when drawing charts.

Code: Pandas series from ndarray.

Output:
Program2

Aim:

Code:

Output:

Program 3

Aim:

Code:
Output:
PRACTICAL NO 4 : Write a Pandas program to shows the attributes of
series.

SOURCE CODE:-

import pandas as pd
import numpy as np
s1 = pd.Series([4.5,7.6,9.5,6.2,6.5])
s2 = pd.Series([3,5,np.NaN], dtype='float32')
s3 = pd.Series([])

print('Values of the Series s1:',s1.values) print('index


of the Series s1:',s1.index)
print('Size of the Series s1:',s1.size)
print('Number of bytes in s1:',s1.nbytes)
print('Check for emptyness in s1:', s1.empty)
print('Check for NaNs in s1:', s1.hasnans)
print('Dtype of the objects:',s1.dtype)
print('***************************************') print('Values
of the Series s2:',s2.values) print('index of the Series
s2:',s2.index)
print('Size of the Series s2:',s2.size)
print('Number of bytes in s2:',s2.nbytes) print('Check
for emptyness in s2:',s2.empty) print('Check for NaNs
in s2:', s2.hasnans) print('Dtype of the
objects:',s2.dtype)
print('***************************************') print('Values
of the Series s3:',s3.values) print('index of the Series
s3:',s3.index)
print('Size of the Series s3:',s3.size)
print('Number of bytes in s3:',s3.nbytes) print('Check
for emptyness in s3:',s3.empty) print('Check for NaNs
in s3:', s3.hasnans) print('Dtype of the
objects:',s3.dtype)
print('***************************************')
PRACTICAL NO 5 : Write a Pandas program to find out the biggest and
smallest three area from given series that stores the area of some states
in km2.

SOURCE CODE:-

import pandas as pd

ser= pd.Series([3456,890,450,67892,34677,7892,56711,\
68291,637632,25723,236,1189,345,256517])
print(ser.values)
print('*************************************')
print('Top 3 Biggest area are:-')
print(ser.sort_values().tail(3))
print('Top 3 Smallest area are:-')
print(ser.sort_values().head(3))
PRACTICAL NO 6: Write a menu driven Pandas program to sort data series
according to the value and index.

SOURCE CODE:-

import pandas as pd
import numpy as np

def Indexasc(s1):
return s1.sort_index(ascending= True)
def Indexdes(s1):
return s1.sort_index(ascending= False)
def Valueasc(s1):
return s1.sort_values(ascending= True)
def Valuedes(s1):
return s1.sort_values(ascending= False)

s1 = pd.Series(data=[100,700,300,900,500]) print(s1)
while 1:
print("="*40)
print("********Main Menu*******")
print("1 for sorting according to the Index (Ascending Order)")
print("2 for sorting according to the Index (Descending Order)")
print("3 for sorting according to the Value (Ascending Order)")
print("4 for sorting according to the Value (Descending Order)")
print("="*40)
n=int(input("Enter your Choice(1,2,3,4): "))
if n==1:
s2=Indexasc(s1)
print(s2)
elif n==2:
s2=Indexdes(s1)
print(s2)
elif n==3:
s2=Valueasc(s1)
print(s2)
elif n==4:
s2=Valuedes(s1)
print(s2)
else:
print("Your choice is Wrong")
ch=input("Y/N : ")
if ch=='n' or ch=='N': break
PRACTICAL NO 7 :Write a Pandas program to create data series and then
change the index of the series objects in any random order.

SOURCE CODE:-

import pandas as pd
import numpy as np
s1 = pd.Series(data=[100,200,300,400,500],index=['a','b','c','d','e'])
print("Original Data")
print(s1) s1=s1.reindex(index=['b','a','c','e','d'])
print(s1)
PRACTICAL NO 8 :Write a Pandas program to add, subtract, multiple and
divide two Pandas Series.

SOURCE CODE:-

import pandas as pd
import numpy as np
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9])
print('Values of series ds1',ds1.values)
print('Values of series ds2',ds2.values)
print('***************************************')
print('Arithmetic Operations')
ds3 = ds1 + ds2
print("Add two Series:",ds3.values)
ds4 = ds1 - ds2
print("Subtract two Series:",ds4.values)
ds5 = ds1 * ds2
print("Multiply two Series:",ds5.values)
ds6 = ds1 / ds2
print("Divide Series1 by Series2:",ds6.values)
PRACTICAL NO 9:Write a Pandas program to Object 1 Population stores
the details of population of Four metro cities of india and Object2
AvgIncome reported in the previous year each of these metro. calculate
income per capita for each of these metro cities.

SOURCE CODE:-

import pandas as
pd import numpy
as np
population = pd.Series([1020010,19821121,2435533,34555252],\
index=['Delhi','kolkata','mumbai','chennei'])
AvgIncome = pd.Series([346356543543,659656966596,56656565586,99569669969],\
index=['Delhi','kolkata','mumbai','chennei'])
percap=AvgIncome/population
print('population in four metroes')
print(population)
print('AvgIncome in four metroes')
print(AvgIncome)
print('percaptal income of four metroes')
print(round(percap,2))
PRACTICAL NO 10 # Write a Python Program to create the dataframe with
following values and perform attributes of dataframe on it.

SOURCE CODE:-

import pandas as pd
data = { 'name': ['Mohak', 'Rajesh', 'Freya', 'Aditya',
'Anika'], 'year': [2012, 2012, 2013, 2014,
2014],
'score': [10, 22, 11, 32, 23],
'catches': [2, 2, 3, 3, 3] }
df = pd.DataFrame(data, columns= ['name','year','score','catches'])
print(df)
print('indexes of dataframe:',df.index)
print('columns of dataframe:',df.columns)
print('size of dataframe:',df.size)
print('shape of dataframe:',df.shape)
print('axes of dataframe:',df.axes)
PRACTICAL NO 11 # Write a Python Program to create the dataframe with
following values and perform head() & tail () Functions on it.

SOURCE CODE:-

import pandas as pd
import numpy as np
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),\
'Age':pd.Series([25,26,25,23,30,29,23]),\
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
df = pd.DataFrame(d)
print("Our data frame is:")
print(df)
print('****************************************************')
print("The first two rows of the data frame is:")
print(df.head(2))
print("The last two rows of the data frame is:")
print(df.tail(2))
PRACTICAL NO 12# Write a Python Program to create the dataframe and
perform Boolean Indexing on it.

SOURCE CODE:-

import pandas as pd

def index1():
print(df.loc[True])
def index2():
print(df.loc[False])

Days=['Monday','Tuesday','Wednesday','Tuesday','Friday']
Classes=[6,0,3,0,8]
dc={'Days':Days,'No.Of Days':Classes}
df=pd.DataFrame(dc,index=[True,False,True,False,True])
print(df)

print("********Main Menu*******")
print("1 Display all record with TRUE index")
print("2 Display all record with FALSE index")
while 1:
n=int(input("Enter your Choice(1,2): "))
if n==1:
print("All records with TRUE index are")
index1()
elif n==2:
print("All record with FALSE index are ")
index2()
else:
print("Your choice is Wrong")
ch=input("Y/N : ")
if ch=='n' or ch=='N': break
PRACTICAL NO 13 # Write a Python Program to create the dataframe and
selecting rows/column using loc and iloc function.

SOURCE CODE:-
import pandas as pd

data={'State':['Andhra','odisha','bihar','jharkhand','W.B'],
'Toys':[4656,5767,6784,1243,5766],
'Books':[34445,45554,45848,56574,56575],
'Uniform':[100,500,500,488,399],
'Shoes':[400,600,688,700,456] }
df=pd.DataFrame(data,columns=['State','Toys','Books','Uniform','Sh
oes'])
print(df)
print('*********************************************')
print('A. Show data of Toys Column')
print(df['Toys'])
print('*********************************************')
print('B. Show data of First 3 rows Toys and Book columns
(using loc)')
print(df.loc[0:3,['Toys','Books']])
print('*********************************************')
print('C. Show data of First 2 rows State,Toys and Books columns (using iloc)')
print(df.iloc[0:2,0:3])
PRACTICAL NO 14 # Write a menudriven program to extract data from
dataframe.
a) Row Wise b) Row Wise Series object (iterrows()).

SOURCE CODE:-

import pandas as pd
import numpy as np

def rowwise():
for(row,rowSeries)in df.iterrows():
print('row index:',row)
print('containing:')
print(rowSeries)
def seriesobj():
for(row,rowSeries)in df.iterrows():
print('row index:',row)
print('containing:')
i=0
for val in rowSeries:
print('AT',i,'Position:',val)
i=i+1

data={'yr1':{'Qtr1':3500,'Qtr2':5600,'Qtr3':3300,'Qtr4':4500},\
'yr2':{'Qtr1':5500,'Qtr2':4600,'Qtr3':6700,'Qtr4':8900},\
'yr3':{'Qtr1':9000,'Qtr2':7800,'Qtr3':7800,'Qtr4':2200}}
df=pd.DataFrame(data)
print(df)
while 1:
print("="*40)
print("********Main Menu*******")
print("1 for extracting data rowwise")
print("2 for extracting data rowwise series object")
print("="*40)
n=int(input("Enter your
Choice(1,2): ")) if n==1:
print("extracting data rowwise ")
rowwise()
elif n==2:
print("extracting data rowwise series object ")
seriesobj()
else:
print("Your choice is Wrong")
ch=input("Y/N : ")
if ch=='n' or ch=='N': break
PRACTICAL NO 15 # Write a menudriven program to extract data from
dataframe
a) Column Wise b) Column Wise Series object (iteritems()).

SOURCE CODE:-

import pandas as pd
import numpy as np

def colwise():
for(col,colSeries)in
df.iteritems():
print('Column index:',col)
print('containing:')
print(colSeries)
def colseriesobj():
for(col,colSeries)in
df.iteritems():
print('col
index:',col)
print('containing:')
i=0
for val in colSeries:
print('AT',i,'Position:',val)
i=i+1

data={'yr1':{'Qtr1':3500,'Qtr2':5600,'Qtr3':3300,'Qtr4':4500},\
'yr2':{'Qtr1':5500,'Qtr2':4600,'Qtr3':6700,'Qtr4':8900},\
'yr3':{'Qtr1':9000,'Qtr2':7800,'Qtr3':7800,'Qtr4':2200}}
df=pd.DataFrame(data)
print(df)
while 1:
print("="*40)
print("********Main Menu*******")
print("1 for extracting data columnwise")
print("2 for extracting data columnwise series object")
print("="*40)
n=int(input("Enter your Choice(1,2,3): "))
if n==1:
print("extracting data columnwise
") colwise()
elif n==2:
print("extracting data columnwise series object ")
colseriesobj()
else:
print("Your choice is Wrong")
ch=input("Y/N : ")
if ch=='n' or ch=='N': break
PRACTICAL 16. Write a program to plot a bar chart in python to
display the result of a school for five consecutive years.

SOURCE CODE:-

import matplotlib.pyplot as pl
year=['2015','2016','2017','2018','2019']# list of years
p=[98.50,70.25,55.20,90.5,61.50] #list of pass
j=['b','g','r','m','c'] # color code of bar charts
pl.bar(year, p, width=0.2, color=j) # bar( ) function to create the
pl.xlabel("year") # label for x-axis
pl.ylabel("Pass%") # label for y-axis
pl.show( ) # function to display bar chart
Practical 17 :- Create multiline chart on common plot where three data
range plotted on same chart. The data range(s) to be plotted are.

data=[[5,25,45,20],[8,1,29,27],[9,29,27,39]]

SOURCE CODE:-

import numpy as np
import matplotlib.pyplot as plt
data=[[5,25,45,20],[8,1,29,27],[9,29,27,39]]
x=np.arange(4)
plt.plot(x,data[0],color='b',label='range 1')
plt.plot(x,data[1],color='g',label='range 2')
plt.plot(x,data[2],color='r',label='range 3')
plt.legend(loc='upper left')
plt.title('Multi range line chart')
plt.xlabel('X')
plt.xlabel('Y')
plt.show()
Practical 18:- Create Bar chart from the given data of Dataframe.

SOURCE CODE:-

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Create a Dictionary of series
d = {'Name':pd.Series(['Sachin','Dhoni','Virat','Rohit','Shikhar']),
'Age':pd.Series([26,25,25,24,31]),
'Score':pd.Series([87,67,89,55
,47])}
#Create a DataFrame
df = pd.DataFrame(d)
print("Dataframe contents")
print (df)
df.plot(kind='barh')
plt.show()
Practical 19:- A survey gathers heights and weight of 50 participates
and recorded the participants age as

Ages=[40,56,46,58,79,70,67,46,32,91,92,93,47,95,69,69,56,50,30,9,29,2
9,0,31,21,14,18,1
6,18,76,68,69,78,81,71,91,71,01,69,78,77,54,59,59,41,51,48,49,7
6,10]

SOURCE CODE:-

import numpy as np
import matplotlib.pyplot as plt
Ages=[40,56,46,58,79,70,67,46,32,91,92,93,47,95,69,69,56,50,30,90,29,29,\
45,31,21,14,18,16,18,76,68,69,78,81,71,91,71,30,69,78,77,\
54,59,59,41,51,48,49,76,10]
plt.hist(Ages,bins=10)
plt.title('Participates Ages Histogram')
plt.show()
Practical 20:- Prof Aasthi is doing some research in the field of
environment. For some purpose.he has generated some data as:

Mu=100
Sigma= 15
X=
mu+sigma*numpy.random.randn(10000)
Y=mu+30*np.random.randn(10000)

SOURCE CODE:-

import numpy as np
import matplotlib.pyplot as plt
mu=100
sigma=15
X= mu+sigma*np.random.randn(10000)
Y=mu+30*np.random.randn(10000)
plt.hist([X,Y],bins=100,histtype='barstacked',cumulative=True)
plt.title('Research Data Histogram')
plt.show()
Practical 21:- Write a program that reads from a csv file (marks.csv
stored in desired location) in a data frame then add a column Total
storing total marks in three subjects and another column for storing
average marks. Print the data frame after adding these columns.

SOURCE CODE:-

import pandas as pd
df=pd.read_csv('c:\\data\marks.csv',names=['Name','Marks1','Marks2','Marks3'])
print('DataFrame after fetching data from csv file')
print(df)
df['Total']=df['Marks1']+df['Marks2']+df['Mar
ks3'] df['AvgMarks']=df['Total']/3
print("Dataframe after Calculation")
print(df)

You might also like