0% found this document useful (0 votes)
21 views15 pages

Series Dataframeboardques

Uploaded by

jainsanjy8
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)
21 views15 pages

Series Dataframeboardques

Uploaded by

jainsanjy8
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/ 15

Lotus Valley School,

Mandsaur
Informatics Practices(Class-
XII)

Practice Questions of
Series and DataFrame
Topics

1. Find the output of following program.


import numpy as np
d=np.array([10,20,30,40,50,60,70])
print(d[-4:])

Ans : [40 50 60 70]

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))

3. Write a suitable Python code to create an empty dataframe.

Ans: import pandas as pd


df=pd.DataFrame()
print(df)

4. Consider the following dataframe : student_df


Name class marks
Anamay XI 95
Aditi XI 82
Mehak XI 65
Kriti XI 45
Write a statement to get the minimum value of the column marks.
Ans Student_df[‘marks’.min()]

5. Write the output of the following code :


import numpy as np
array1=np.array([10,12,14,16,18,20,22])
print(array1[1:5:2])
Ans [12 16 ]

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”)

8. Write a code in python to find the minimum value in a list.


Example:
If the List contains: [100,150,90,65,180,200]
Then the output should be: Minimum Value is 65
Ans: List=[100,150,90,65,180,200]
min=List[0]
for i in List:
if i<min:
min=i
print(“Minimum Value is”, min)

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]

Ans import pandas as pd


# initialize list of lists
data = [['S101', 'Amy', 70], ['S102', 'Bandhi', 69], ['S104', 'Cathy', 75], ['S105', 'Gundaho', 82]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Marks'])
# printdataframe. print(df )

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())

16. Given a data frame df1 as shown below:


City Maxtemp MinTemp RainFall
Delhi 40 32 24.1
Bengaluru 31 25 36.2
Chennai 35 27 40.8
Mumbai 29 21 35.2
Kolkata 39 23 41.8
(i) Write command to compute sum of every column of the data frame.
(ii) Write command to compute mean of column Rainfall.
(iii) Write command to compute Median of the Maxtemp Column.

Ans: (i) df1.sum()


(ii) df1[‘Rainfall’].mean()
(iii) df1.loc[:, ‘Maxtemp’].median( )

17. Find the output of the following code:


import pandas as pd
data = [{'a': 10, 'b': 20},{'a': 6, 'b': 32, 'c': 22}]
#with two column indices, values same as dictionary keys
df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])
#With two column indices with one index with other name
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print(df1)
print(df2)
Ans a b
first 10 20
second 6 32
a b1
first 10 NaN
second 6 NaN

18. Write the code in pandas to create the following dataframes :


df1 df2
mark1 mark2 mark1 mark2
0 10 15 0 30 20
1 40 45 1 20 25
2 15 30 2 20 30
3 40 70 3 50 30
Write the commands to do the following operations on the dataframes given above :
(i) To add dataframes df1 and df2.
(ii) To subtract df2 from df1
(iii) To rename column mark1 as marks1in both the dataframes df1 and df2.
(iv) To change index label of df1 from 0 to zero and from 1 to one.

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))

(iii) df1.rename(columns={'mark1':'marks1'}, inplace=True)


print(df1)
(iv) df1.rename(index = {0: "zero", 1:"one"}, inplace = True)
print(df1)

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’]

20. Consider a given Series , M1:

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.

Ans a. will give the output as:


[20,40,90,110,20,40,90,110]

b. will give the output as


0 40
1 80
2 180
3 220
Justification: In the first statement x represents a list so when a list is multiplied by a number, it
is replicated that many number of times.
The second y represents a series. When a series is multiplied by a value, then each element of
the series is multiplied by that number.

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.

Ans import matplotlib.pyplot as plt


Classes = ['VII','VIII','IX','X']
Students = [40,45,35,44]
plt.bar(classes, students)
plt.show()

24. Write a program in Python Pandas to create the following DataFrame batsman from a
Dictionary:

Perform the following operations on the DataFrame :


1)Add both the scores of a batsman and assign to column “Total”
2)Display the highest score in both Score1 and Score2 of the DataFrame.
3)Display the DataFrame

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']))

25.What will be the output of the given code?


import pandas as pd
s = pd.Series([1,2,3,4,5],
index=['akram','brijesh','charu','deepika','era'])
print(s['charu'])
Ans output- 3

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

31. Consider the following series named animal:

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.

34. Write the output of the given program:


import pandas as pd
S1=pd.Series([5,6,7,8,10],index=['v','w','x','y','z'])
l=[2,6,1,4,6]
S2=pd.Series(l,index=['z','y','a','w','v'])
print(S1-S2)
a.

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)

36. Write the output of the given command:


import pandas as pd
s=pd.Series([1,2,3,4,5,6],index=['A','B','C','D','E','F'])
print(s[s%2==0])
a.
B 0
D 0
F 0
dtype: int64
b.
A 1
B 2
C 5
dtype: int64
c.
B 2
D 4
F 6
dtype: int64
d.
B 1
D 2
F 3
dtype: int64

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:

Output Required: (3,5)


a. print(df.shape())
b. print(df.shape)
c. print(df.size)
d. print(df.size())
Ans b. print(df.shape)

39. Write the output of the given command:


df1.loc[:0,'Sal']
Consider the given dataframe.

a. 0 Kavita 50000 3000


b. 50000
c. 3000
d. 50000
Ans
b. 50000

40. Consider the following data frame name df

Write the output of the given command:


print(df.marks/2)
a. 0 45.0
1 NaN
2 43.5
Name: Marks,
dtype: float64
b. 0 45.0
1 NaN
2 43
Name: Marks,
dtype: float64
c. 0 45
1 NaN
2 43.5
Name: Marks,
dtype: float64
d. 0 45.0
1 0
2 43.5
Name: Marks,
dtype: float64
Ans
a.
0 45.0
1 NaN
2 43.5
Name: Marks, dtype: float64

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)

Output of the above code:

Based on the given information, answer the questions NO. 1-5.


1. He wants to add a new column with name of student ‘Prem’ in above data frame choose the right
command to do so:
a. DF['Prem']=[89,78,76]
b. df['Prem']=[89,78,76]
c. DF['Prem']=[89,78,76,67]
d. DF['Name']=[89,78,76]

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)

5. What will be the output of the given command?

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.

42. What will be the output of the given command?

Naveen Rehana John Roja M


a
n
n
a
t
A 90 92 89 81
B 91 81 91 71
C 97 96 88 67
print(DF.size)
a. 15
b. 18
c. 21
d. 23
Ans a. 15

You might also like