Series Dataframeboardques
Series Dataframeboardques
Mandsaur
Informatics Practices(Class-
XII)
Practice Questions of
Series and DataFrame
Topics
2. Fill in the blank with appropriate numpy method to calculate and print the covariance of an array.
import numpy as np
data=np.array([1,2,3,4,5,6])
print(np. (data,ddof=0))
Ans:print(np.cov(data,ddof=0))
6. Write a code to plot a bar chart to depict the pass percentage of students in CBSE exams for the years 2015 to
2018 as shown below-
Ans:
import matplotlib.pyplot as plt
import numpy as np
objects=(‘2015’, 2016’, ‘2017’, ‘2018’)
y_pos=np.arrange(len(objects))
percentage=[82,83,85,90]
plt.bar(y_pos, percentage, align=’Centre’,
color=’Blue’)
plt.xticks(y_pos,objects)
plt.ylabel(“Pass Percentage”)
plt.xlabel(‘Years’)
plt.show()
7. Write a code in Python to search for a given value in a list of elements(Without using in-built function)
Example:
If the List contains: [20,30,40,50,60,80,120]
and the element to be searched is:60
Then the output should be: Found at position 4
Ans:
List=[20,30,40,60,80,120]
Flag=0
No=int(Input(“Enter a value”))
pos=0
for I in List:
if no==i:
prnt(“Found at position=”, pos+1)
Flag=1
break
pos=pos+1
if Flag==0:
print(“value not found”)
9. Hitesh wants to display the last four rows of the data frame df and has written the following code :
df.tail()
But last 5 rows are being displayed. Identify the error and rewrite the correct code so that last 4 rows get
displayed.
Ans df.tail(4)
10. A dataframe studdf stores data about the students stream, marks. A part of it is shown below:
Class Stream Marks
11 Science 95
11 Commerce 80
11 Arts 75
11 Vocational 65
Using the above dataframe, write the command to compute Average marks stream wise.
Ans Studdf.pivot_table(index=’Stream’, Values=’marks’, aggfunc=’mean’)
11. Consider the following python code and write the output for statement S1
import pandas as pd
K=pd.Series([2,4,6,8,10,12,14])
K.quantile([0.50,0.75]) ---------------------- S1
Ans 0.50 8.0
0.75 11.0
12. Write a small python code to drop a row from dataframe labeled as 0.
Ans: df = df.drop(0)
print(df )
13. Write a python code to create a dataframe with appropriate headings from
the list given below :
['S101', 'Amy', 70], ['S102', 'Bandhi', 69], ['S104', 'Cathy', 75], ['S105', 'Gundaho', 82]
14. Write a small python code to create a dataframe with headings(a and b) from the list given below :
[[1,2],[3,4],[5,6],[7,8]]
Ans
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
df = df.append(df2)
15. Consider the following dataframe, and answer the questions given below:
import pandas as pd
df = pd.DataFrame({“Quarter1":[2000, 4000, 5000, 4400, 10000], "Quarter2":[5800, 2500, 5400, 3000, 2900],
"Quarter3":[20000, 16000, 7000, 3600, 8200], "Quarter4":[1400, 3700, 1700, 2000, 6000]})
(i) Write the code to find mean value from above dataframe df over the index and column axis.
(ii) Use sum() function to find the sum of all the values over the index axis.
(iii) Find the median of the dataframe df.
Ans: i) print(df.mean(axis = 1))
print(df.mean(axis = 0))
(ii) print(df.sum(axis = 1))
(iii) print(df.median())
Ans:
import numpy as np
import pandas as pd
df1 = pd.DataFrame({'mark1':[30,40,15,40], 'mark2':[20,45,30,70]});
df2 = pd.DataFrame({'mark1':[10,20,20,50], 'mark2':[15,25,30,30]});
print(df1)
print(df2)
(i) print(df1.add(df2))
(ii) print(df1.subtract(df2))
19. Consider the following DataFrame df and answer any four questions from (i)-(v)
rollno name UT1 UT2 UT3 UT4
1 Prerna Singh 24 24 20 22
2 Manish Arora 18 17 19 22
3 Tanish Goel 20 22 18 24
4 Falguni Jain 22 20 24 20
5 Kanika Bhatnagar 15 20 18 22
6 Ramandeep Kaur 20 15 22 24
i. Write down the command that will give the following output.
a. print(df.max)
b. print(df.max())
c. print(df.max(axis=1))
d. print(df.max, axis=1)
Ans b. print(df.max())
ii.
The teacher needs to know the marks scored by the student with roll number 4. Help her
to identify the correct set of statement/s from the given options :
a. df1=df[df[‘rollno’]==4]
print(df1)
b. df1=df[rollno==4]
print(df1)
c. df1=df[df.rollno=4]
print(df1)
d. df1=df[df.rollno==4]
print(df1)
Ans
a. df1=df[df[‘rollno’]==4]
print(df1)
d. df1=df[df.rollno==4]
print(df1)
iii. Which of the following statement/s will give the exact number of values in each column of
the dataframe?
i. print(df.count())
ii. print(df.count(0))
iii. print(df.count)
iv. print(df.count(axis=’index’))
Ans both (i) and (ii)
iv. Which of the following command will display the column labels of the DataFrame?
a. print(df.columns())
b. print(df.column())
c. print(df.column)
d. print(df.columns)
Ans d. print(df.columns)
v. Ms. Sharma, the class teacher wants to add a new column, the scores of Grade with the
values, ‘ A’, ‘B’, ‘A’, ‘A’, ‘B’, ‘A’ ,to the DataFrame. Help her choose the command to do so:
a. df.column=[’A’,’B’,’A’,’A’,’B’,’A’]
b. df [‘Grade’]=[’A’,’B’,’A’,’A’,’B’,’A’]
c. df.loc[‘Grade’]= [’A’,’B’,’A’,’A’,’B’,’A’]
d. Both (b) and (c) are correct
Ans b. df [‘Grade’]=[’A’,’B’,’A’,’A’,’B’,’A’]
Marks
Term1 45
Term2 65
Term3 24
Term4 89
Write a program in Python Pandas to create the series.
Ans import pandas as pd
m1=pd.Series([45,65,24,89],index=['term1','term2','term3','term4'])
21. Cconsider two objects x and y. x is a list whereas y is a Series. Both have values 20, 40,90,
110.
What will be the output of the following two statements considering that the above objects have
been created already
a. print (x*2) b. print(y*2)
Justify your answer.
22. Consider the following graph . Write the code to plot it.
Ans import matplotlib.pyplot as plt
plt.plot([2,7],[1,6])
plt.show()
alternative answer
import matplotlib.pyplot as plt
a = [1,2,3,4,5,6]
b = [2,3,4,5,6,7]
plt.plot (a,b)
23. Draw the following bar graph representing the number of students in each class.
24. Write a program in Python Pandas to create the following DataFrame batsman from a
Dictionary:
import pandas as pd
d1={'B_NO':[1,2,3,4],
'Name':["Sunil Pillai","Gaurav Sharma","Piyush Goel","Kartik
Thakur"],'Score1':[90,65,70,80], 'Score2':[80,45,95,76]}
df=pd.DataFrame(d1)
print(df)
df['Total'] = df['Score1']+ df['Score2']
Alternative Answer
Scheme
df['Total'] = sum(df['Score1'], df['Score2'])
print(df)
print("Maximum scores are : " ,max(df['Score1']),max(df['Score2']))
26. Assuming the given series, named stud, which command will be used to print 5 as output?
Amit 90
Ramesh 100
Mahesh 50
john 67
Abdul 89
Name: Student, dtype: int64
a. stud.index
b. stud.length
c. stud.values
d. stud.size
Ans output- stud.size
27. A social science teacher wants to use a pandas series to teach about Indian historical monuments and its
states. The series should have the monument names as values and state names as indexes which are stored in
the given lists, as shown in the code. Choose the statement which will create the series:
import pandas as pd
Monument=['Qutub Minar','Gateway of India','Red Fort','Taj Mahal']
State=['Delhi','Maharashtra','Delhi','Uttar Pradesh']
a. S=df.Series(Monument,index=State)
b. S=pd.Series(State,Monument)
c. S=pd.Series(Monument,index=State)
d. S=pd.series(Monument,index=State)
Ans c. S=pd.Series(Monument,index=State)
28. Observe the following figure. Identify the coding for obtaining this as output.
a. import matplotlib.pyplot as plt
plt.plot([1,2],[4,5])
plt.show()
b. import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,1])
plt.show()
c. import matplotlib.pyplot as plt
plt.plot([2,3],[5,1])
plt.show()
d. import matplotlib.pyplot as plt
plt.plot([1,3],[4,1])
plt.show()
Ans option b
29. Read the statements given below and identify the right option to draw a histogram.
Statement A: To make a Histogram with Matplotlib, we can use the plt.hist() function.
Statement B: The bin parameter is compulsory to create histogram.
a. Statement A is correct
b. Statement B is correct
c. Statement A is correct, but Statement B is incorrect
d. Statement A is incorrect, but Statement B is correct
Ans c. Statement A is correct, but Statement B is incorrect
30. Which graph should be used where each column represents a range of values, and the height of a column
corresponds to how many values are in that range?
a. plot
b. line
c. bar
d. histogram
Ans d. histogram
Ans
W Wolf
B Bear
dtype: object
32. What is a correct syntax to return the values of first row of a Pandas DataFrame? Assuming the name of
the DataFrame is dfRent.
a. dfRent[0]
b. dfRent.loc[1]
c. dfRent.loc[0]
d. dfRent.iloc[1]
Ans: c. dfRent.loc[0]
33. Difference between loc() and iloc().:
a. Both are Label indexed based functions.
b. Both are Integer position-based functions.
c. loc() is label based function and iloc() integer position based function.
d. loc() is integer position based function and iloc() index position based function.
Ans c. loc() is label based function and iloc() integer position based function.
a 0
v -1.0
w 2.0
x NaN
y 2.0
z 8.0
dtype: float64
b.
a NaN
v -1.0
w 2.0
x NaN
y 2.0
z 8.0
dtype: float64
c.
v -1.0
w 2.0
y 2.0
z 8.0
dtype: float64
d.
a NaN
v -1.0
w 2.0
x 3.0
y 2.0
z 8.0
dtype: float64
Ans
b
a NaN
v -1.0
w 2.0
x NaN
y 2.0
z 8.0
dtype: float64
35. Which command will be used to delete 3 and 5 rows of the data frame. Assuming the data frame name as
DF.
a. DF.drop([2,4],axis=0)
b. DF.drop([2,4],axis=1)
c. DF.drop([3,5],axis=1)
d. DF.drop([3,5])
Ans: a DF.drop([2,4],axis=0)
Ans:
c
B2
D4
F6
dtype: int64
37. Ritika is a new learner for the python pandas, and she is aware of some concepts of python. She has
created some lists, but is unable to create the data frame from the same. Help her by identifying the statement
which will create the data frame.
import pandas as pd
Name=['Manpreet','Kavil','Manu','Ria']
Phy=[70,60,76,89]
Chem=[30,70,50,65]
a. df=pd.DataFrame({"Name":Name,"Phy":Phy,"Chem":Chem})
b. d=("Name":Name,"Phy":Phy,"Chem":Chem)
df=pd.DataFrame(d)
c. df=pd.DataFrame([Name,Phy,Chem],columns=['Name',"Phy","Chem","Total"])
d. df=pd.DataFrame({Name:"Name", Phy :"Phy",Chem: "Chem"})
Ans a. df=pd.DataFrame({"Name":Name,"Phy":Phy,"Chem":Chem})
38. Assuming the given structure, which command will give us the given output:
41. Mr. Sharma is working with an IT company, and he has provided some data. On which he wants to do
some operations, but he is facing some problem, help him:
Code:
import pandas as pd
ResultSheet={ 'Naveen': pd.Series([90,91,
97],index=['Maths','Science','Hindi']),
'Rehana': pd.Series([92, 81, 96],
index=['Maths','Science','Hindi']),
'John': pd.Series([89, 91, 88],
index=['Maths','Science','Hindi']),
'Roja': pd.Series([81, 71, 67],
index=['Maths','Science','Hindi']),
'Mannat': pd.Series([94, 95, 99],
index=['Maths','Science','Hindi'])}
DF = pd.DataFrame(ResultSheet)
print(DF)
2. He wants to set all the values to zero in data frame, choose the right command to do so:
a. DF=0
b. DF[]=0
c. DF[:]=0
d. DF[:]==0
3.He wants to delete the row of science marks:
a. DF.drop('Science', axis=1)
b. DF.drop('Science', axis=0)
c. DF.drop('Science', axis=-1)
d. DF.drop('Science', axis==0)
4. The following code is to create another data frame, which he wants to add to the existing Data frame.
Choose the right command to do so:
Sheet1={
'Aaradhya': pd.Series([90, 91, 97],
index=['Maths','Science','Hindi'])}
S1=pd.DataFrame(Sheet1)
a. DF.append(S1,axis=0)
b. DF.append(S1)
c. DF.insert(S1)
d. DF.join(S1)
DF.index=['A','B','C']
Ans
1. a. DF['Prem']=[89,78,76]
2. c DF[:]=0
3. b. DF.drop('Science', axis=0)
4. b. DF.append(S1)
5. b.