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

Info Fair record

The document contains a series of Python programming exercises focused on creating and manipulating pandas Series and DataFrames. It includes tasks such as creating Series for countries and student percentages, performing mathematical operations on Series, and visualizing data with graphs. Each exercise is accompanied by code examples and expected outputs.

Uploaded by

j2492618
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Info Fair record

The document contains a series of Python programming exercises focused on creating and manipulating pandas Series and DataFrames. It includes tasks such as creating Series for countries and student percentages, performing mathematical operations on Series, and visualizing data with graphs. Each exercise is accompanied by code examples and expected outputs.

Uploaded by

j2492618
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Informatics

Fair Record

Term-I
By:___________________________
Class:__________
Roll no:______

1
Q1) Write a program in python to create a series called countries
with data of 5 GCC countries.
Ans)
import pandas as pd
countries=pd.Series(["Kuwait","Saudi","Dubai","Bahrain","Iran"])
print(countries)

Output)

2
Q2) To write a python program to create a Series to store 5 students’
percentage. Using dictionary and print all the element that are
above 75 percent.
Ans)
import pandas as pd
D={'Arun':65,'Bala':91,'Charan':74,'Dinesh':80,'Usha':85}
s=pd.Series(D)
print(s[s>75])

Output)

3
Q3) Write a Python program to create a series object the stores the
employee names as index and their salary as values.
Ans)
import pandas as pd
import numpy as np
Section=['A','B','C']
Contribution=np.array([6700,5500,np.nan])
s=pd.Series(data=Contribution, index=Section)
print(s)

Output)

4
Q4) To write a python program to create a series object that stores
the initial budget allocated (50000/-each) for the 4 quarter of the
year: Qtr1, Qtr2, Qtr3, Qtr4.
Ans)
import pandas as pd
Budget=pd.Series(50000,index=['Qtr1','Qtr2','Qtr3','Qtr4'])
print(Budget)

Output)

5
Q5) To write a python program to create a series object with
employee names as the index and their salaries as values. Accept the
names of the employess whose salary needs to be changed, along
with the new salary and update it in the series.
Ans)
import pandas as pd
D={'John':50000,'Bala':60000,'Anu':55000,'Birundha':52000}
S=pd.Series(D)
print("Employees salary before updating")
print(S)
print('\n')
opt=input("Do you want to update the salary of the employee (y/n)?: ")
if opt=='y':
Name=input("Enter the name of the employee: ")
if Name in S:
new_salary=float(input("Enter the new salary: "))
S[Name]=new_salary
print("\nSalary update successfully")
print("\nEmployees salary after updating")
print(S)
else:
print("\nEmployees not found in the records")
else:
print("\nThank You")

6
Output)

7
Q6) To write a Python program to create a Series using list and
display the following attributes of the series (i)Index (ii)datatype
(iii)size (iv)shape (v)has NaN
Ans)
import pandas as pd
L=[10,45,67,3,43]
S=pd.Series (L,index=['a','b','c','d','e'])
print("The index of series is:",S.index)
print("The data type of the series is:",S.dtype)
print("The size of the series is:",S.size)
print("The shape of the series is :",S.shape)
print("The NaN of the series is :",S.NaN)

Output)

8
Q7) To create a python program to perform following mathematical
operations on two series object: (i)Addition (ii)Subtraction
(iii)Multiplication (iv)Division
Ans)
import pandas as pd
S1=pd.Series([10,20,30],index=['a','b','c'])
S2=pd.Series([2,5],index=['a','b'])
print("The Addition of two series object is: ")
print(S1+S2)
print("The Subtraction of two series object is: ")
print(S1-S2)
print("The Mulitiplication of two series object is: ")
print(S1*S2)
print("The Division of two series object is: ")
print(S1/S2)

Output)

9
[same program with fill value as 10]
Ans)
import pandas as pd
S1=pd.Series([10,20,30],index=['a','b','c'])
S2=pd.Series([2,5],index=['a','b'])
print("The Addition of two series object is: ")
print(S1.add(S2,fill_value=10))
print("The Subtraction of two series object is: ")
print(S1.sub(S2,fill_value=10))
print("The Mulitiplication of two series object is: ")
print(S1.mul(S2,fill_value=10))
print("The Division of two series object is: ")
print(S1.div(S2,fill_value=10))

Output)

10
Q8) Display the number of row and columns in a DataFrame.
Ans)
import pandas as pd
exam_data={'Name':['Anastasia','Dima','Katherine'],
'Score':[12.5,9,16.5],
'Attempt':[1,3,2],
'Qualify':['yes','no','yes']}
labels=['a','b','c']
df=pd.DataFrame(exam_data,index=labels)
print(df)
total_rows=(len(df.axes[0]))
total_columns=(len(df.axes[1]))
print('total_rows','total_columns')

Output)

11
Q9) Create a dataframe for examination result and display row
labels, column labels and datatype of each column and the
dimensions.
Ans)
import pandas as pd
dic={'Class':['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'],
'Pass_Percentage':[100,100,100,100,100,100,100,100,100,98.6,100,99]}
result=pd.DataFrame(dic)
print(result)
print(result.dtypes)
print('shape of the frame is: ')
print(result.shape)
print(result.info())

Output)

12
Q10) To write a python program to create a panda’s DataFrame
called DF for the following table Using Dictionary of List to perform
the following operations:

Toys Books Uniforms Shoes

AP 7916 61896 610 8110

OD 8508 8208 508 6798

M.P 7226 6149 611 9611

U.P 7617 6157 457 6457

(i)To display only column “TOYS” from DataFrame DF

(ii)To Display the row details of “AP” and “OD” from DataFrame
DF

(iii)To Display the column “BOOKS” and “UNIFORM” for ‘MP’


and ‘UP’ from DataFrame DF

(iv)To Display consecutive 3 rows and 3 columns from DataFrame


DF
(v)Insert a new column ‘Bags’ with values as [5891, 8625, 9785,
4475]
(vi)Delete the row details of MP from DataFrame

13
Ans)
import pandas as pd
D={'Toys':[7916,8508,7226,7617],
'Books':[61896,8208,6149,6157],
'Uniform':[610,508,611,457],
'Shoes':[8810,6798,9611,6457]}
DF=pd.DataFrame(D,index=['AP','OD','MP','UP'])
print("The details of Toys are:")
print(DF.loc[:,'Toys'])
print("\n")
print("The details of AP and OD are:")
print(DF.loc['AP':'OD',])
print("\n")
print("The details of MP and UP are:")
print(DF.loc['MP':'UP'])
print("\n")
print("Consecutive 3 rows and 3 columns are:")
print(DF.iloc[0:3,0:3])
print('\n')
DF['Bags']=[5891,8628,9785,4475]
print(DF)
print('\n')
DF=DF.drop('MP',axis=0)
print(DF)

14
Output)

15
Q11) Create a DataFrame named ‘Airways’ and solve the questions:
1.To extract data from Air India to Indigo for all columns
2. to extract details of indigo flight
3.extract the number of passengers in all flights
4.extract all details for all flights
5.extract year and passengers number of all flights in month of jan

Ans)
import pandas as pd
data={'Year':[2018,2019,2020,2021,2022], 'Month':['Jan','Feb','Mar','Apr','May'],
'Passengers':[25,30,45,67,56]}
Airways=pd.DataFrame(data,index=['Air India','Kuwait Airways','Jet Airways
','Indigo','Air Arabia'])
print(Airways)
print("\n")
print(Airways.loc ['Air India':'Indigo','Year':'Passengers'])
print("\n")
print(Airways.loc['Indigo'])
print("\n")
print(Airways.loc[:,'Passengers'])
print("\n")
print(Airways.loc[:,:])
print("\n")
print(Airways[['Year','Passengers']][Airways['Month']=='Jan'])
Output)

16
17
Q12) Write a program to select the rows where the number of
attempts in the examination is greater than 2
Ans)
import pandas as pd
import numpy as np
exam_data={'Name':
['Anastasia','Dima','Katherine','James','Emily','Micheal','Matheew','Laura','Kevin','J
ames'],
'Scores':[12.5,9,16.5,np.nan,9,220,14.5,np.nan,9,19],
'Attempts':[1,3,2,3,2,3,1,1,2,1],
'Qualify':['yes','no','yes','no','no','yes','yes','no','no','yes']}
labels=['a','b','c','d','e','f','g','h','i','j']
df=pd.DataFrame(exam_data,index=labels)
print("Number of attempts in the examination is greater than 2")
print(df)
print(df["Attempts"]>2)
print(df[df["Attempts"]>2])

Output)

18
Q13) Replace all non-numeric values with 0 in a DataFrame.
Ans)

import pandas as pd

import numpy as np

exam_data={'Name':
['Anastasia','Dima','Katherine','James','Emily','Micheal','Matheew','Laura','Kevin','J
ames'],

'Scores':[12.5,9,16.5,np.nan,9,20,14.5,np.nan,9,19],

'Attempts':[1,3,2,3,2,3,1,1,2,1],

'Qualify':['yes','no','yes','no','no','yes','yes','no','no','yes']}

labels=['a','b','c','d','e','f','g','h','i','j']

df=pd.DataFrame(exam_data,index=labels)

print("Number of attempts in the examination is greater than 2")

print(df)

df=df.fillna(0)

19
print("\nNew DataFrame replacing the NaN with 0")

print(df)

Output)

20
Q14) Insert a specific column at a given index
Ans)
import pandas as pd

21
d={'col2':[4,5,6,9,5],'col3':[7,8,12,1,11]}
df=pd.DataFrame(data=d)
print('Original DataFrame:')
print(df)
new_col=[1,2,3,4,7]
idx=0
df.insert(loc=idx,column='co1',value=new_col)
print('\nNew Dataframe:')
print(df)

Output)

Q15) Draw a line graph representing the percentage of marks for


each person,
a. Set the appropriate label for x-axis and y-axis.
b. Set the title of the graph “Percentage Comparison.”

22
Ans)
import matplotlib.pyplot as plt
x_values=['Anu','Hari','Riya']
y_values=[40,50,45]
plt.plot(x_values,y_values,linewidth='1',ls='dashdot',color='r',marker='*')
plt.xlabel('Names')
plt.ylabel('Marks')
plt.title('Percentage of Marks')
plt.savefig('D:\percentagecomparison_trial')
plt.show()

Output)

Q16) Write a program to draw the line graph


a. Set the appropriate label for x-axis and y-axis.
b. Set the title of the graph “Number of Students.”
c. Show the grid line.

23
Ans)
import matplotlib.pyplot as plt
x=[1.00,2.00,3.00]
y=[4.0,5.0,1.0]
plt.plot(x,y,linewidth='1',color='b')
plt.xlabel('x value')
plt.ylabel('y value')
plt.title('Number of students')
plt.savefig("numberofstudents_trial")
plt.grid()
plt.show()

Output)

Q17) Write a program to draw a bar graph


Ans)
import matplotlib.pyplot as plt
import numpy as np

24
Names=['Amit','Mohan','Sudha']
X=np.arange(len(Names))
Maths=[100,95,85]
Science=[100,50,90]
SST=[60,57.48,53.58]
plt.bar(X,Maths,color='red',width=.25,label='Mat')
plt.bar(X+.25,Science,color='yellow',width=.25,label='Sci')
plt.bar(X+.50,SST,color='green',width=.25,label='SST')
plt.xlabel('Names',fontsize=15)
plt.ylabel('Names',fontsize=15)
plt.legend()
plt.show()

Output)

Q18) Drawing multiple line graph together.


Ans)
import matplotlib.pyplot as plt
Names=['Amit','Mohan','Sudha']

25
Maths=[100,95,85]
Science=[100,50,90]
SST=[60,57.48,53.58]
plt.plot(Names,Maths,color='red',ls='dashdot',marker='*',linewidth=1.5,label='Mat'
)
plt.plot(Names,Science,color='yellowq',ls='dashed',marker='o',linewidth=1.5,label
='Sci')
plt.plot(Names,SST,color='green',ls='dashdot',marker='D',linewidth=1.5,label='SS
T')
plt.title('Result Analysis',fontsize=15)
plt.xlabel('Names',fontsize=15)
plt.ylabel('Names',fontsize=15)
plt.legend()
plt.show()

Output)

Q19) Draw a histogram.


Ans)
import matplotlib.pyplot as plt
import numpy as np

26
data=[1,11,21,31,41]
plt.hist([5,15,25,35,45,55], bins=[0,10,20,30,40,50,60], weights=[20,10,45,33,6,8],
edgecolor='red')
plt.show()

Output)

Q20) Draw a histogram using horizontal orientation.


Ans)
import matplotlib.pyplot as plt
data=[1,11,21,31,41,51,61]

27
plt.hist(data,bins=7,weights=[0,10,20,30,40,50,60],edgecolor='red',orientation='hor
izontal')
plt.show()

Output)

28

You might also like