0% found this document useful (0 votes)
71 views19 pages

Suryadatta National School Class 12 CBSE Informatics Practices Practicals List

This document contains 13 questions related to Python Pandas practicals. Each question provides a programming problem and expected output. The problems involve tasks like creating DataFrames, adding/modifying columns, slicing data, aggregating data, plotting charts etc. Sample code and output is provided for each question.

Uploaded by

Om Jagdeesh
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 views19 pages

Suryadatta National School Class 12 CBSE Informatics Practices Practicals List

This document contains 13 questions related to Python Pandas practicals. Each question provides a programming problem and expected output. The problems involve tasks like creating DataFrames, adding/modifying columns, slicing data, aggregating data, plotting charts etc. Sample code and output is provided for each question.

Uploaded by

Om Jagdeesh
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/ 19

Suryadatta National School

Class 12 CBSE

Informatics Practices Practicals List

Name : Om Jagdeesh
Roll No : 44
Std : XII

Q1) Write a program that creates Series from ndArray. Print all values in the Series using
loop and also print the sliced values from the Series.

Program:
import numpy as np
arr = np.array([1,5,13,21,12,3,15,9,4,11])
for x in arr:
print(x) #prints all values of series using loop
slc=arr[2:6]
print("The slice of the array from 2 to 6 is: {}".format(slc)) #Prints
slice from 2 to 6

Output:
Q2) Write a program that create reads marks in Series and prints the finds average of
Marks.

Program:
import numpy as np
import pandas as pd
n = int(input('Enter the number of elements and then enter the marks '))
lst = []
for i in range(0,n):
x = int(input())
lst.append(x) #input marks
Marks = pd.Series(lst) #converting list to Series
print('The averge of marks is')
print(Marks.mean())

Output:
Q3) Create a Data Frame quarterly sales where each row contains the item category, item
name, and expenditure. Group the rows by the category and print the total expenditure
per category. (Read 3 values for each category. Total category should be 4).

Program:
import numpy as np
import pandas as pd
d1 = {

'ItemCategory':['Phone','AC','Fridge','TV'],
'ItemName':['iPhone12','Hitachi','Samsung','Sony'],
'Expenditure':[80000,35000,40000,100000]
}
QuarterlySales = pd.DataFrame(d1)
print(QuarterlySales)
print('-----------')
df2 = QuarterlySales.groupby('ItemCategory')
print('Total Expenditure per category')
print(df2[['ItemCategory','Expenditure']].sum())

Output:
Q4) Create a data frame for examination result and display row labels, column labels data
types of each column and the dimensions.

Program:
import numpy as np
import pandas as pd
d1={
'Maths':[75,80,95,98],
'Physics':[88,63,92,90],
'Chemistry':[70,82,78,97],
'English':[90,70,98,95],
'IP':[92,60,98,92]
}
df = pd.DataFrame(d1,index = ['Soham','Raj','Payal','Rahul'])
print(df)
print(df.shape) #Dimension of DataFrame

Output:
Q5) Create a DataFrame as shown below and perform following operations on it.

a) Add a new column Total Price that contains Total Price of Product (Total Price
= Quantity * Price)
b) Add a new row to the DataFrame with Data – (Scanner, HP, 2, 9500)
c) Display the Product and Total Price of the DataFrame.

Program:
import numpy as np
import pandas as pd
d1={

'Product':['CPU','Mouse','Keyboard','Printer','Hard Disk','Plotter'],
'Company':['Compaq','Dell','HP','Epson','Toshiba','Sony'],
'Quantity':[40,20,15,5,10,5],
'Price':[9000,500,500,5700,2000,8000]
}
df = pd.DataFrame(d1)
df['Total Price']=df.Quantity*df.Price
df.at[6]={'Product':'Scanner', 'Company':'HP', 'Quantity':2, 'Price':9500}
print(df)
print("---------------------")
print(df[['Product','Total Price']]) #Final Result
Output:

Q6) Create a DataFrame that reads Employee Data (Employee No, Name, Address, Date of
Joining, Salary) from CSV File and displays the details.

Program:
import pandas as pd
import numpy as np
df=pd.read_csv('C:\\Users\\Shilpa\\Documents\\om\\EmployeeData.csv',sep=';)
print(df)

Output:
Q7) Create a DataFrame with details BookID, Book Description, Author, Publisher,
Quantity and Price. Store the data into a CSV File with name “Employee_Data”.

Program:
import numpy as np
import pandas as pd
d1={
'BookID':[8085,4397,5080,3495,2096,4121],
'Book Description':['The Alchemist','Mathematical Circles','Dune','Harry
Potter','The Diary of a Wimpy kid','A Brief history of Time'],
'Author':['Paulo Coelho','Dimitrii Fomin','Frank Herbert','J.K
Rowling','Jeff Kinney','Stephen Hawking'],
'Publisher':['Harper Collins','Springer','Springer','Bloomsbury
Publishing','Puffin Books','Cambridge Press'],
'Quantity':[20,12,5,15,9,13],
'Price':[200,120,350,400,120,300]
}
df = pd.DataFrame(d1)
df.to_csv('C:\\Users\\Shilpa\\Documents\\om\\Employee_Data.csv')

Output:
Q8) Consider DataFrame df as shown below :

Write commands to :
a) Write command to calculate minimum value for each of the row from subset of
dataframe that contains age, weight, height, runs scored
b) Write a command to calculate the mean for the last 3 rows.

Program:
import numpy as np
import pandas as pd
d1={

'name':['mayur','anil','viraj','viraj','mahesh','viraj'],
'age' :[15,16,17,17,16,17],
'weight':[51,48,49,51,48,59],
'height':[5.1,5.2,5.1,5.3,5.1,5.3],
'runsscored':[55,25,71,53,51,50]
}
df = pd.DataFrame(d1)
df2 = df[['age','weight','height','runsscored']]
print(df2.min(axis=0))
print('--------------------')
print(df2.iloc[3:,:].min(axis=0))

Output:
Q9) Write a code to create the following dataframe.

Do the following:
a) Add column "Total Amount" that calculates total amount of tickets and assign that to
new column.
b) Add a new row with values ( B006 , Vijay, 7, 150, John). Calculate the total amount of
tickets and assign it to the Total Amount column.

Program:
import numpy as np
import pandas as pd
pd.set_option('display.expand_frame_repr', False)

d1={

'Booking Code':['B001','B002','B003','B004','B005'],
'Customer Name':['Veer','Umesh','Lavanya','Shobhana','Piyush'],
'No of Ticket':[4,2,6,5,3],
'Ticket Rate':[100,200,150,250,100],
'Booking Clerk':['Manish','KIshor','Manish','John','Kishor']
}
df = pd.DataFrame(d1)
df['Total Amount'] = df['No of Ticket']*df['Ticket Rate']
print(df)
print('-------------------')
df.at[5]={'Booking Code':'B006', 'Customer Name':'Vijay', 'No of Ticket':7,
'Ticket Rate':150, 'Booking Clerk':'John'}
df['Total Amount'] = df['No of Ticket']*df['Ticket Rate']
print(df)
Output:

Q10) Read the subjects and marks/grades for different subjects of Class 12 and plot
column chart on that. Also display title, x-axis and y-axis labels.

Program:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
Subjects = ['Maths','Physics','Chemistry','English','IP']
Marks = [88,95,72,89,90]
plt.title('Subject Marks')
plt.bar(Subjects,Marks)
plt.xlabel('Subjects')
plt.ylabel('Marks')
plt.show()
Output:
Q11) Read data from open source (e.g. data.gov.in), aggregate and summarize it. Then
plot it using different plotting functions of the Matplotlib library.

Program:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('C:\\Users\\Shilpa\\Documents\\om\\population_by_country_202
0.csv', sep=',')
df2 = df.sort_values(by = ['Population'], ascending = False)
df3 = df2.head(10)
plt.pie(df3.Population, labels=df3.Country, autopct ='%1.1f%%')
plt.axis('equal')
plt.title('%Population share of Ten most populous countries')
plt.show()

Output:
Q12) Draw the histogram based on the Production of Corn in different Years
'Year':2003,2005,2007,2009,2011,2013,2015,2017,2019,2021
'Production': 7,4,9,19,23,4,16,8,6,25

Program:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
production = [7,4,9,19,23,4,16,8,6,25]
year=['2003','2005','2007','2009','2011','2013','2015','2017','2019','2021]
plt.bar(year,production)
plt.title('Production of Corn: 2003-2021')
plt.xlabel('Year')
plt.ylabel('Production')
plt.show()

Output:
Q13) Observe the given data for Football Players and their goals scored in the matches.
Plot them on the bar chart.

Program:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
playerName = ['Ronaldo','Pele','Messi','Gerd Muller','Eusebio','Maravilla']
goalsScored = [783,767,755,735,623,575]
plt.bar(playerName,goalsScored)
plt.title('Goals scored by Foootball players')
plt.xlabel('Player Name')
plt.ylabel('Goals Scored')
plt.show()

Output:
Q14) Consider the data given below for creating bar and line chart

a) Create a bar chart to distribution of rainfall from June to Nov for all zones.
b) Create a line chart to observe any trends from June to Nov.

a) Program:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
d1 = {

'Zones':['North','South','East','West','Central'],
'June':[140,160,140,180,110],
'July':[130,200,180,190,160],
'Aug' :[130,130,130,200,130],
'Sept':[190,200,170,120,110],
'Oct' :[160,170,190,180,170],
'Nov' :[200,190,180,190,130]
}
df = pd.DataFrame(d1)
df.plot(kind='bar')
plt.title('Distribution of rainfall from June to November')
plt.show()
Output:

b) Program:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.plot([140,130,130,190,160,200],label='North')
plt.plot([160,200,130,200,170,190],label='South')
plt.plot([140,180,130,170,190,180],label='East')
plt.plot([180,190,200,120,180,190],label='West')
plt.plot([110,160,130,110,170,130],label='Central')
plt.legend()
plt.title('Rainfall trends from June to November')
plt.xlabel('Months')
plt.ylabel('Rainfall')
plt.show()
Output:
Q15) Write a program in Python Pandas to create the following DataFrame ‘Library’.

a) Display DataFrame ‘Library’.


b) Display the Book names having price above 350.

Program:
import numpy as np
import pandas as pd
pd.set_option('display.expand_frame_repr', False)
d1={

'Bid':['B01','B02','B03','B05','B06'],
'Name':['Wings of Fire','The Monk who sold his Ferrari','You Can
Win','Who moved my cheese','Real Success'],
'Author':['A.P.J Abdul Kalam','Robin Sharma','Shiv Khera','Spencer
Jhonson','Pattrick Mather Pike'],
'Price':[450,370,350,450,250],
'Mem_Name':['Pranjal','Kunal','Rajat','Roma','Sia'],

'Issue_Date':['2021-04-11','2021-03-15','2021-04-18','2021-02-27','2021-04-
23'],
'Status':['Not Returned','Returned','Not Returned','Returned','Not
Returned']
}
Library = pd.DataFrame(d1)
print(Library)
print('----------------')
df2 = Library[Library['Price']>350]
print('The books with price above 350 are:')
print(df2.Name)
Output:

You might also like