0% found this document useful (0 votes)
72 views23 pages

Practical Record Programs - Solutions

Uploaded by

dhiyu00
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)
72 views23 pages

Practical Record Programs - Solutions

Uploaded by

dhiyu00
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/ 23

Python Programming with Solutions

1. Create a series S1 from an array containing even numbers less


than or equal to 15 with index labels as 2, 4, 6,……
Source Code
import pandas as pd
S1=pd.Series(range(2,15,2), index= range(2, 15, 2))
print (S1)

Output
2 2
4 4
6 6
8 8
10 10
12 12
14 14
dtype: int64

2. Create a series from a dictionary of values and a ndarray.


Source Code
import pandas as pd
import numpy as np
print("Creating Series using ndarray:")
nda=np.arange(1, 10, 2)
S1=pd.Series(nda)
print(S1)
print("Creating Series using dictionary:")
S2= pd.Series({"India": "New Delhi",
"Japan": "Tokyo",
"UK": "London"})
print(S2)

Output
Creating Series using ndarray:
0 1
1
1 3
2 5
3 7
4 9
dtype: int32
Creating Series using dictionary:
India New Delhi
Japan Tokyo
UK London
dtype: object

3. Section (sect) A, B, C, D, E and contribution (contri) made is


respectively (6700, 5600, 5000, 5200, nil) for a charity. Write
code to create a series that stores the contribution amount as the
values and section names as the indexes with datatype as float32.
The contribution of each section will be doubled when the series
is printed.
Source Code
import pandas as pd
import numpy as np
section=['A', 'B', 'C', 'D', 'E']
contri=np.array([6700, 5600, 5000, 5200, np.NAN])
S=pd.Series(data=contri*2, index=section, dtype=np.float32)
print(S)

Output
A 13400.0
B 11200.0
C 10000.0
D 10400.0
E NaN
dtype: float32

2
4. Create a series that stores the area of some states (10 values)in
km2.
Write a code to find out the biggest and the smallest three areas
from the series.
Source Code
import pandas as pd
Area=[15000, 34000, 55000, 14000, 38000, 67000, 450000,
78900, 27000, 100000]
S=pd.Series(Area)
print("Area in ascending order: ")
print(S.sort_values())
print("The largest 3 areas are: ")
print(S.tail(3))
print("The smallest 3 areas are: ")
print(S.head(3))

Output
Area in ascending order:
3 14000
0 15000
8 27000
1 34000
4 38000
2 55000
5 67000
7 78900
9 100000
6 450000
dtype: int64
The largest 3 areas are:
7 78900
8 27000
9 100000
dtype: int64
The smallest 3 areas are:
3
0 15000
1 34000
2 55000
dtype: int64

5. Create a series of ages below hundred and find out the ages that
are more than 50.
Source Code
import pandas as pd
Ages=[15, 34, 55, 64, 38, 87, 45, 78, 27, 100]
S=pd.Series(Ages)
print("Ages in Series : ")
print(S)
print("The Series with ages more than 50: ")
print(S[S>50])
Output
Ages in Series :
0 15
1 34
2 55
3 64
4 38
5 87
6 45
7 78
8 27
9 100
dtype: int64
The Series with ages more than 50:
2 55
3 64
5 87
7 78
9 100
dtype: int64
4
6. Number of students in classes 11 and 12 in three streams
(‘Science’, ‘Commerce’ and ‘Humanities’) are stored in two
series S11 and S12. Write code to find total number of students
in classes 11 and 12 stream wise.
Source Code
import pandas as pd
#creating series objects
S11= pd.Series(data=[30,40,50], index=['Science', 'Commerce',
'Humanities'])
print("Number of students in 11 : ")
print(S11)
print()
S12= pd.Series(data=[37,44,45], index=['Science', 'Commerce',
'Humanities'])
print("Number of students in 12 : ")
print(S12)
print()
#adding two objects to get total number of students
print("Total number of students : ")
print(S11+S12)

Output
Number of students in 11 :
Science 30
Commerce 40
Humanities 50
dtype: int64

Number of students in 12 :
Science 37
Commerce 44
Humanities 45
dtype: int64

5
Total number of students :
Science 67
Commerce 84
Humanities 95
dtype: int64

7. Create a dataframe ITEMS from a list of dictionaries containing


Item No, Item Name and Price of five items.
Source Code
import pandas as pd
Dict={'ItemNo' : [100,101,102,103,104], 'IName' : ['Pen',
'Pencil', 'Book', 'Eraser', 'Marker'], 'Price':[15, 5, 35, 3, 30]}
ITEMS=pd.DataFrame(Dict, index=[1, 2, 3, 4, 5])
print(ITEMS)

Output
ItemNo IName Price
1 100 Pen 15
2 101 Pencil 5
3 102 Book 35
4 103 Eraser 3
5 104 Marker 30

8. Consider an array with values 10,20,30,40,50. Create a series


from this array with default indexes and write python statements
for the following.
a. Set the values of all elements to 100
b. Create a new series with index values from ‘A’ to ‘E’.
c. Add 10 to all elements of the series and display it.
d. Display 1st and 4th elements of the series.
e. Set the value of 3rd element to 500.
Source Code
import pandas as pd
Array = [10,20,30,40,50]
6
S=pd.Series(Array)
print(S)

Output
0 10
1 20
2 30
3 40
4 50
dtype: int64
1. S[:6]=100
Output
0 100
1 100
2 100
3 100
4 100
dtype: int64
2. S1=pd.Series(Array, index=['A', 'B', 'C', 'D', 'E'])
Output
A 10
B 20
C 30
D 40
E 50
dtype: int64
3. S1[:6]=S1+10
Output
A 20
B 30
C 40
D 50
E 60
dtype: int64
4. print(S1[0])
7
print(S1[3])
Output
10
40
5. S1[2]=500
Output
A 10
B 20
C 500
D 40
E 50
dtype: int64

9. Create the following dataframe using Series.


Name Marks Age
Vijaya 80 32
Rahul 92 28
Meghana 67 30
Radhika 95 25
Sara 97 20
Source Code
import pandas as pd
import numpy as np
Name = pd.Series(['Vijaya', 'Rahul', 'Meghana', 'Radhika',
'Sara'])
Marks = pd.Series([80,92,67,95,97])
Age = pd.Series([32,28,30,25,20])
Dict={'Name':Name, 'Marks':Marks, 'Age':Age}
DF=pd.DataFrame(Dict)
print(DF)

Output
Name Marks Age
0 Vijaya 80 32
1 Rahul 92 28
8
2 Meghana 67 30
3 Radhika 95 25
4 Sara 97 20

10. Create two dataframes df1 and df2, and perform mathematical
operations. (+, -, *, /).
Source Code
import pandas as pd
import numpy as np
N1 = {'No1':[500, 800, 400, 600], 'No2':[200, 300, 100, 400]}
N2 = {'No1':[1000, 600, 500, 800], 'No2':[200, 300, 100, 400]}
DF1=pd.DataFrame(N1)
DF2=pd.DataFrame(N2)
#Addition
print("Sum of 2 DataFrames :")
print(DF1+DF2)
#Subtraction
print("Difference of 2 DataFrames :")
print(DF1-DF2)
#Multiplication
print("Product of 2 DataFrames :")
print(DF1*DF2)
#Division
print("Quotient of 2 DataFrames :")
print(DF1/DF2)

Output
Sum of 2 DataFrames :
No1 No2
0 1500 400
1 1400 600
2 900 200
3 1400 800
9
Difference of 2 DataFrames :
No1 No2
0 -500 0
1 200 0
2 -100 0
3 -200 0
Product of 2 DataFrames :
No1 No2
0 500000 40000
1 480000 90000
2 200000 10000
3 480000 160000
Quotient of 2 DataFrames :
No1 No2
0 0.500000 1.0
1 1.333333 1.0
2 0.800000 1.0
3 0.750000 1.0

11. Create a dataframe for examination result and display the


following:
a. Row labels
b. Column labels
c. Data Types of Each Column
d. Dimensions
e. No. of Rows and Columns
f. Total no. of elements in the dataframe
g. Transpose of the dataframe
Source Code
import pandas as pd
import numpy as np
Dict = {'RNo':[1, 2, 3, 4], 'Name':['Alok', 'Babitha', 'Deepak',
'Geethu'],
'Marks':[500, 600, 450, 300], 'Grade':['A', 'A+', 'B', 'C']}
DF1=pd.DataFrame(Dict, index=['one', 'two', 'three', 'four'])
10
print(DF1)
# Row Labels
print ("Row Labels")
print(DF1.index)
# Column Labels
print ("Column Labels")
print(DF1.columns)
# Data Type Details
print ("Data Types of Each Column")
print(DF1.dtypes)
# Dimensions
print("Dimension = ",DF1.ndim)
#No. of Rows and Columns
print ("No. of Rows and Columns = ")
print(DF1.shape)
# Total no. of elements in the dataframe
print("Total no. of elements in the dataframe = ")
print(DF1.size)
#Transpose of the dataframe
print("Transpose of the dataframe: ")
print(DF1.T)

Output
RNo Name Marks Grade
one 1 Alok 500 A
two 2 Babitha 600 A+
three 3 Deepak 450 B
four 4 Geethu 300 C
Row Labels
Index(['one', 'two', 'three', 'four'], dtype='object')
Column Labels
Index(['RNo', 'Name', 'Marks', 'Grade'], dtype='object')
Data Types of Each Column
RNo int64
Name object
11
Marks int64
Grade object
dtype: object
Dimension = 2
No. of Rows and Columns = (4, 4)
Total no. of elements in the dataframe = 16
Transpose of the dataframe =
one two three four
RNo 1 2 3 4
Name Alok Babitha Deepak Geethu
Marks 500 600 450 300
Grade A A+ B C

12. Create a dataframe with RollNo, Name, Mark1 and Mark2 of 5


students with default index. Write the commands to do the
following operations on the dataframes.
1. Change the index from default to ‘one’, ‘two’ etc.
2. Calculate the total marks and display in the fileld ‘Total’.
3. Add a new row to the dataframe.
4. Display the details of 1st and 3rd students.
5. Apply iteration to read all rows and columns.
6. Delete 6th record from the dataframe.
Source Code
import pandas as pd
import numpy as np
Dict = {'RNo':[1, 2, 3, 4, 5], 'Name':['Alok', 'Babitha', 'Deepak',
'Geethu', 'Rohan'],
'Mark1':[80, 60, 45, 30, 50], 'Mark2':[50, 60, 55, 85, 70]}
DF1=pd.DataFrame(Dict)
print(DF1)
DF1=pd.DataFrame(Dict, index=['one', 'two', 'three',
'four','five'])
print(DF1)
DF1['Total'] = DF1['Mark1']+DF1['Mark2']
print(DF1)
12
DF1.loc[ 'six', : ]= [ 6,'Sonu', 85, 90, 175]
print(DF1)
print(DF1.loc[['one', 'three']])
#Reading all rows in the dataframe
for (row, rowSeries) in DF1.iterrows():
print("Row Index: ", row)
print("Containing")
print(rowSeries)
#Reading all columns in the dataframe
for (col, colSeries) in DF1.iteritems():
print("Column Index: ", col)
print("Containing")
print(colSeries)
DF1.drop(["six"], inplace=True)
print(DF1)

Output
RNo Name Mark1 Mark2
0 1 Alok 80 50
1 2 Babitha 60 60
2 3 Deepak 45 55
3 4 Geethu 30 85
4 5 Rohan 50 70
RNo Name Mark1 Mark2
one 1 Alok 80 50
two 2 Babitha 60 60
three 3 Deepak 45 55
four 4 Geethu 30 85
five 5 Rohan 50 70
RNo Name Mark1 Mark2 Total
one 1 Alok 80 50 130
two 2 Babitha 60 60 120
three 3 Deepak 45 55 100
four 4 Geethu 30 85 115
five 5 Rohan 50 70 120
13
RNo Name Mark1 Mark2 Total
one 1.0 Alok 80.0 50.0 130.0
two 2.0 Babitha 60.0 60.0 120.0
three 3.0 Deepak 45.0 55.0 100.0
four 4.0 Geethu 30.0 85.0 115.0
five 5.0 Rohan 50.0 70.0 120.0
six 6.0 Sonu 85.0 90.0 175.0
RNo Name Mark1 Mark2 Total
one 1.0 Alok 80.0 50.0 130.0
three 3.0 Deepak 45.0 55.0 100.0
Row Index: one
Containing
RNo 1
Name Alok
Mark1 80
Mark2 50
Total 130
Name: one, dtype: object
Row Index: two
Containing
RNo 2
Name Babitha
Mark1 60
Mark2 60
Total 120
Name: two, dtype: object
Row Index: three
Containing
RNo 3
Name Deepak
Mark1 45
Mark2 55
Total 100
Name: three, dtype: object
Row Index: four
14
Containing
RNo 4
Name Geethu
Mark1 30
Mark2 85
Total 115
Name: four, dtype: object
Row Index: five
Containing
RNo 5
Name Rohan
Mark1 50
Mark2 70
Total 120
Name: five, dtype: object
Row Index: six
Containing
RNo 6
Name Sonu
Mark1 85
Mark2 90
Total 175
Name: six, dtype: object
Column Index: RNo
Containing
one 1.0
two 2.0
three 3.0
four 4.0
five 5.0
six 6.0
Name: RNo, dtype: float64
Column Index: Name
Containing
one Alok
15
two Babitha
three Deepak
four Geethu
five Rohan
six Sonu
Name: Name, dtype: object
Column Index: Mark1
Containing
one 80.0
two 60.0
three 45.0
four 30.0
five 50.0
six 85.0
Name: Mark1, dtype: float64
Column Index: Mark2
Containing
one 50.0
two 60.0
three 55.0
four 85.0
five 70.0
six 90.0
Name: Mark2, dtype: float64
Column Index: Total
Containing
one 130.0
two 120.0
three 100.0
four 115.0
five 120.0
six 175.0
Name: Total, dtype: float64
RNo Name Mark1 Mark2 Total
one 1.0 Alok 80.0 50.0 130.0
16
two 2.0 Babitha 60.0 60.0 120.0
three 3.0 Deepak 45.0 55.0 100.0
four 4.0 Geethu 30.0 85.0 115.0
five 5.0 Rohan 50.0 70.0 120.0

13. Create a dataframe with Boolean index and access data using
loc() and iloc().
Source Code
import pandas as pd
Days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday']
Classes = [6, 4, 0, 5, 0, 2]
Dict={'Days':Days, 'No of Classes': Classes}
ClsDF=pd.DataFrame(Dict, index=[True, True, False, True,
False,True])
print(ClsDF)
#Accessing True Values using loc
print(ClsDF.loc[True])
#Accessing Values using iloc
print(ClsDF.iloc[1:4])

Output
Days No of Classes
True Monday 6
True Tuesday 4
False Wednesday 0
True Thursday 5
False Friday 0
True Saturday 2
Days No of Classes
True Monday 6
True Tuesday 4
True Thursday 5
True Saturday 2
Days No of Classes
17
True Tuesday 4
False Wednesday 0
True Thursday 5

14. Write a program to draw line chart for the following: Show the
unemployment rate from 1920 to 2010.
Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8, 12, 8, 7.2, 6.9, 7, 6.5, 6.2, 5.5, 6.3]
Source Code
import matplotlib.pyplot as plt
Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8, 12, 8, 7.2, 6.9, 7, 6.5, 6.2, 5.5, 6.3]
#plotting Line Graph
plt.plot(Year, Unemployment_Rate, 'm+', markersize=7,
markeredgecolor='green', linewidth=4, linestyle='dashed')
# set the X axis and Y axis Labels
plt.xlabel('Year')
plt.ylabel('Unemployment_Rate')
#set title for the graph
plt.title('Unemployment Rate Line Chart')
plt.figure(figsize=(15,7))
plt.show()

Output

18
15. Write a program to plot a bar chart for the following and
apply attributes and labels: objects=["Python", "C++", "Perl",
"Java", "VB"] performance = [10,8,6,3,1]
Source Code
import matplotlib.pyplot as plt
Objects=["Python", "C++", "Perl", "Java", "VB"]
Performance = [10,8,6,3,1]
#plotting Bar Graph
plt.bar(Objects,Performance, color=['red', 'green','b','m','y'])
# set the X axis and Y axis Labels
plt.xlabel('Objects')
plt.ylabel('Performance')
#set title for the graph
plt.title('Performance Bar Graph')
plt.figure(figsize=(10,5))
plt.show()

Output

16. Create an array having 25 elements between 5 and 50. Plot


a histogram having 10 bins.
Source Code
import matplotlib.pyplot as pl
19
array=[1, 9, 15, 17, 19, 20, 22, 23, 25, 26, 29, 30, 31, 33, 34, 36,
37, 39, 40, 42, 43, 45, 47, 49, 50]
pl.hist( array, bins=10, histtype='barstacked',
orientation='horizontal')
pl.title("Histogram")
pl.show()

Output

17. Create a dataframe with Names and Marks of 3 subjects


scored by 5 students. Analyze and plot appropriate chart with
title and legend.
Source Code
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
Names=['Aryan', 'Batul', 'Darshan', 'Gautham', 'Hitanshu']
EngMarks = [57, 84, 96, 39, 60]
MathMarks = [97, 64, 86, 59, 70]

20
ScienceMarks = [89, 94, 100, 79, 80]
Dict={'Names':Names, 'EngMarks': EngMarks,
'MathMarks':MathMarks, 'ScienceMarks':ScienceMarks}
DF=pd.DataFrame(Dict, index=[1, 2, 3, 4, 5])
print(DF)
X=np.arange(len(Names))
#plotting Bar Graph
plt.bar(Names, EngMarks, width=.15, label= 'English' )
plt.bar(X+0.15, MathMarks, width=.15, label= 'Math' )
plt.bar(X+0.30, ScienceMarks, width=.15, label= 'Science' )
#set the legend
plt.legend(loc='upper right')
# set the X axis and Y axis Labels
plt.xlabel('Names of Students')
plt.ylabel('Marks')
#set title for the graph
plt.title('Students Result Bar Graph')
plt.figure(figsize=(10,5))
plt.show()

Output

21
Names EngMarks MathMarks ScienceMarks
1 Aryan 57 97 89
2 Batul 84 64 94
3 Darshan 96 86 100
4 Gautham 39 59 79
5 Hitanshu 60 70 80

18. Write a python program to read/import from a CSV file


Employee.csv and create a dataframe from it.
Source Code
import pandas as pd
empdf=pd.read_csv("C:\\Users\\Desktop\\Employee.csv " )
print(empdf)

Output
Eno Ename Designation Salary
0 1 Arun Manager 50000
1 2 Meena Teacher 30000
2 3 Sarith Doctor 75000
3 4 Tarun Officer 25000
4 5 Vihan Clerk 5000

19. Consider the dataframe DF as shown below.


Names EngMarks MathMarks ScienceMarks
1 Aryan 57 97 89
2 Batul 84 64 94
3 Darshan 96 86 100
4 Gautham 39 59 79
5 Hitanshu 60 70 80
Write a python program to write/export the contents of this
dataframe to a CSV file.
Source Code
import pandas as pd
import matplotlib.pyplot as plt

22
import numpy as np
Names=['Aryan', 'Batul', 'Darshan', 'Gautham', 'Hitanshu']
EngMarks = [57, 84, 96, 39, 60]
MathMarks = [97, 64, 86, 59, 70]
ScienceMarks = [89, 94, 100, 79, 80]
Dict={'Names':Names, 'EngMarks': EngMarks,
'MathMarks':MathMarks, 'ScienceMarks':ScienceMarks}
DF=pd.DataFrame(Dict, index=[1, 2, 3, 4, 5])
print(DF)
DF.to_csv("C:\\Users\\Desktop\\Employee1.csv")

Output
Names EngMarks MathMarks ScienceMarks
1 Aryan 57 97 89
2 Batul 84 64 94
3 Darshan 96 86 100
4 Gautham 39 59 79
5 Hitanshu 60 70 80

Employee1.csv
,Names,EngMarks,MathMarks,ScienceMarks
1,Aryan,57,97,89
2,Batul,84,64,94
3,Darshan,96,86,100
4,Gautham,39,59,79
5,Hitanshu,60,70,80

********************************

23

You might also like