0% found this document useful (0 votes)
35 views43 pages

IP Practical File Q & A 2024-25

Ip practical record

Uploaded by

rohitjr20
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)
35 views43 pages

IP Practical File Q & A 2024-25

Ip practical record

Uploaded by

rohitjr20
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/ 43

Manish Kumar Sharma – IP – Practical File

Q 1 : Given a dictionary “Dict1”:


Dict1 = {'India': 'NewDelhi', 'UK':'London', 'Japan': 'Tokyo'}
write pandas code to create Series “Sr” using dictionary “Dict1”. Also
display output of it.

Answer :
import pandas as pd
Dict1 = {'India': 'NewDelhi', 'UK':'London', 'Japan': 'Tokyo'}
Sr = pd.Series(Dict1)
print(Sr)

# Output
India NewDelhi
UK London
Japan Tokyo
dtype: object

[NOTE : Dictionary keys can be used to construct an index for a


Series.]

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 2 : Given a Series “Sr”:
Sr = pd.Series(['NewDelhi', 'WashingtonDC', 'London', 'Paris'],
index=['India', 'USA', 'UK', 'France'])
Write code to do following :
i) to access 1st element of Series “Sr”.
ii) to access last 2 elements.
iii) to access Series in reverse order

Answer :
i)
print(Sr['India']) # using labelled index
or
print(Sr[0]) # using positional index
ii)
print(Sr[[2,3]])
or
print(Sr[['UK', 'France']])
or
print(Sr['UK' : 'France']) # using slicing
or
print(Sr[2 : 4]) # using slicing
or
print(Sr.tail(2))
iii)
print(Sr[ : : -1])

[Note : 1. Two common ways for accessing the elements of a series:


Indexing and Slicing.
2. Indexes are of two types: positional index and labelled index.
Positional index takes an integer value that corresponds to its
position in the series starting from 0, whereas labelled index takes
any user-defined label as index.]

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 3. Given a Series “Sr”:
Sr = pd.Series(['NewDelhi', 'WashingtonDC', 'London', 'Paris'],
index=['India', 'USA', 'UK', 'France'])
Write code to do following :
i) to access top 2 elements.
ii) alter row-index value with [10, 20, 30, 40]

Answer :
i) print(Sr[[0,1]])
or
print(Sr[['India', 'USA']])
or
print(Sr['India' : 'USA']) # using slicing
or
print(Sr[0 : 2]) # using slicing
or
print(Sr.head(2))
ii)
Sr.index = [10,20,30,40]

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 4. Given a Series “Sr”:
Sr = pd.Series(['NewDelhi', 'WashingtonDC', 'London', 'Paris'],
index=['India', 'USA', 'UK', 'France'])
What will be the output of following:
print(Sr['India' : 'USA']) # 1
print(Sr[0 : 1]) # 2
Justify your answer.

Answer :
# 1
India NewDelhi
USA WashingtonDC
dtype: object
# 2
India NewDelhi
dtype: object
Justification :
Slicing : [startIndex : endIndex : step]
If labelled indexes are used for slicing, then value at the “endindex”
label is also included in the output.
When we use positional indices for slicing, the value at the “endindex”
position is excluded.

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 5 . Given a Series “Sr”:
a 10
b 11
c 12
d 13
e 14
f 15
dtype: int32
Sr[1:3] = 50
print(Sr) # 1
Sr[‘b’:’d’] = 50
print(Sr) # 2
Write output of above code. Also justify the answer.

Answer :
# 1
a 10
b 50
c 50
d 13
e 14
f 15
dtype: int32

# 2
a 10
b 50
c 50
d 50
e 14
f 15
dtype: int32

Justification :
Slicing : [startIndex : endIndex : step]
When we use positional indices for slicing, the value at the “endindex”
position is excluded.
If labelled indexes are used for slicing, then value at the “endindex”
label is also included in the output.

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 6. Given a List “vals” and a Series “Sr”:
vals = [ 10, 11, 12 ] # or ( 10, 11, 12 ]
Sr = pd.Series(vals)
What will be the output of following code:
print(vals * 2) # 1
print(Sr * 2) # 2
Also justify your answer.

Answer :
# 1
[10, 11, 12, 10, 11, 12]

# 2
0 20
1 22
2 24

Justification :
“vals” is a list (or tuple) object. When we use it with “*”
(replication) operator, it replicates the structure of list (tuple).
“Sr” is a series object. Series supports vectorization it means –
while using arithmetic operator with a series object, it does
manipulation element-wise instead of manipulating structure.

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 7. Given a List “vals” and a Series “Sr”:
vals = [ 10, 11, 12, 13 ]
Sr = pd.Series(vals)
What will be the output of following code:
print(Sr % 2 == 0) # 1
print(Sr[ Sr % 2 == 0 ]) # 2
Also justify your answer.

Answer :
# 1
0 False
1 False
2 True
3 True
# 2
0 10
2 12

Justification : Applying comparison operator directly on Series object


works in vectorized way i.e., applies this check on each element and
then returns True/False for each element.
But when this check is applied in the form <Series Object>[ <Boolean
Expression>], then it returns filtered result containing only the
elements that return True for the given Boolean expression.

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 8. Write code to complete following for Series “Sr”:
i) to display index(axis labels) of the Series
ii) to return Series as ndarray or ndarray
iii) to return a tuple with no of values in Series
iv) to return the number of bytes in the underlying data
v) to return the number of dimensions of the underlying data
vi) to return the number of elements/values in the underlying data
vii) to return the size of the dtype of the item of the underlying
data
viii) to check if Series contains any NaN value
ix) to check if Series is empty
x) to assign a name “NewSr” to the Series object.
xi ) to return the number of non-NaN values in the Series.

Answer :
i) print(Sr.index)
ii) print(Sr.values)
iii) print(Sr.shape)
iv) print(Sr.nbytes)
v) print(Sr.ndim)
vi) print(Sr.size)
vii) print(Sr.itemsize)
viii) print(Sr.hasnans)
ix) print(Sr.empty)
x) Sr.name = “NewSr”
print(Sr)
xi) print(Sr.count())

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 9. Given Series objects : “Series1” & “Series2”
Series1 Series2
a 1 z 10
b 2 y 20
c 3 a -10
d 4 c -50
e 5 e 100
dtype: int64 dtype: int64
Write output of following statements:
(i) Series1 + Series2
(ii) Series1.add(Series2, fill_value=10)
Justify your answer.

Answer :
(i) Series1 + Series2
index Series1 Series2 Series1 + Series1
a 1 -10 -9.0
b 2 NaN
c 3 -50 -47.0
d 4 NaN
e 5 100 105.0
y 10 NaN
z 20 NaN
a -9.0
b NaN
c -47.0
d NaN
e 105.0
y NaN
z NaN
dtype: float64
[Note : here that the output of addition is NaN if one of the elements
or both elements have no value.]
(ii) Series1.add(Series2, fill_value=0)
index Series1 Series2 Series1 + Series1
a 1 -10 -9.0
b 2 10 12
c 3 -50 -47.0
d 4 10 14
e 5 100 105.0
y 10 10 20
z 10 20 30
a -9.0
b 12.0
c -47.0
d 14.0
e 105.0
Manish Kumar Sharma – IP – Practical File
Manish Kumar Sharma – IP – Practical File
y 20.0
z 30.0
dtype: float64
Jstification :
We can use the series method add() and a parameter fill_value to
replace missing value with a specified value. By calling
series1.add(series2) is equivalent to calling series1 + series2, but
add() allows explicit specification of the fill value for any element
in series1 or series2 that might be missing.
Table of answer (ii), shows the changes in the series elements and
corresponding output after replacing missing values by 0.
Just like addition [function - add()], subtraction [function - sub()],
multiplication [function - mul()] and division [function - div()] can
also be done using corresponding mathematical operators or explicitly
calling of the appropriate method.

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 10. Write pandas code to create an empty DataFrame “dFrameEmt”. Also
display output of code.

Answer :
import pandas as pd
dFrameEmt = pd.DataFrame()
dFrameEmt

Output :
Empty DataFrame
Columns: []
Index: []

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 11. Write pandas code to create DataFrame using
(i). dictionary of lists,
(ii) list of lists (nested list), and
(iii) dictionary of series objects
using following data:
Rno Name Score1 Score2
0 11 Preeti 80 99
1 12 Priyansh 90 98
2 13 Rohit 100 100

Answer :
# (i) - USING DICTIONARY
import pandas as pd
data1 = { 'Rno' : [11, 12, 13],
'Name' : ['Preeti', 'Priyansh', 'Rohit'],
'Score1' : [80, 90, 100],
'Score2' : [99, 98, 100] }
Student1 = pd.DataFrame(data1)
print(Student1)
# (ii) - USING NESTED LIST
data2 = [ [11, 'Manish', 90, 99],
[12, 'Mahesh', 87, 97],
[13, 'Raman', 100, 100] ]
Student2 = pd.DataFrame(data2,
columns=['Rno', 'Name', 'Score1', 'Score2'])
print(Student2)
# (iii) - USING SERIES OBJECTS
import pandas as pd
data3 = { 'Rno' : pd.Series([11, 12, 13]),
'Name' : pd.Series(['Preeti', 'Priyansh', 'Rohit']),
'Score1' : pd.Series([80, 90, 100]),
'Score2' : pd.Series([99, 98, 100])}
Student3 = pd.DataFrame(data3)
print(Student3)

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 12. Consider the following dataframe “Student1”:
Rno Name Score1 Score2
0 1 Preeti 80 99
1 2 Priyansh 90 98
2 3 Rohit 100 100
Write pandas code to do following :
(i) add a new column 'Total' with sum of 'Score1' and 'Score2'
(ii) add a new record with appropriate values

Answer :
(i) add a new column 'Total' with sum of 'Score1' and 'Score2'
Student1['Total'] = Student1['Score1'] + Student1['Score2']
Or
Student1['Total'] = Student1[['Score1','Score2']].sum(axis=1)
Or
Student1['Total'] = Student1.Score1 + Student1.Score2
Or
Student1.loc[ : , 'Total'] = Student1['Score1'] +
Student1['Score2']
(ii) add a new record with appropriate values
Student1.loc[3] = [4, 'Manish', 98, 99]
Or
Student1.loc[3, :] = [5, 'Akshat', 98, 99]
Or
Student1.iloc[3, :] = [5, 'Akshat', 98, 99]

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 13. Consider the following dataframe “Student1”:
Rno Name
0 1 Preeti
1 2 Priyansh
2 3 Rohit
Write pandas code to do following:
(i) Add a new column “City” with value [“Jaipur”, “Jodhpur”, “Ajmer”].
(ii) Add a new Column “State” with value “Rajasthan”.
(iii) Change “Priyansh” with “Pawan”.
(iv) To display DataFrame “Student1”.

Answer :
(i)
Student1['City'] = [“Jaipur”, “Jodhpur”, “Ajmer”]
Or
Student1.loc[ : , 'City'] = [“Jaipur”, “Jodhpur”, “Ajmer”]
(ii)
Student1['State'] = “Rajasthan”
Or
Student1.loc[ : , 'State'] = “Rajasthan”
(iii)
Student1.loc[ Student1['Name'] == ’Priyansh’, ‘Name’] = ‘Pawan’
Or
Student1.loc[1, ‘Name’] = ‘Pawan’
(iv)
print(Student1)
Or
print(Student1.loc[ : ])
Or
print(Student1.loc[ : , : ]

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 14. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write pandas code to do following:
(i) to display Arnab’s scores
(ii) to display Arnab and Riya’s scores
(iii) to display performance in maths of each student
(iv) to display performance in maths & Hindi of each student
(v) to display performance in maths & Hindi of Ramit & Riya

Answer :
(i)
print(Student1.Arnab)
Or
print(Student1[‘Arnab’])
Or
print(Student1.loc[:, ‘Arnab’])
(ii)
print(Student1[[‘Arnab’, ‘Riya’]])
Or
print(Student1.loc[:, [‘Arnab’, ‘Riya’]])
(iii)
print(Student1.loc[‘Maths’])
Or
print(Student1.loc[‘Maths’, :])
Or
print(Student1.iloc[0])
Or
print(Student1.head(1))
(iv)
print(Student1.loc[[‘Maths’, ‘Hindi’]])
Or
print(Student1.loc[[‘Maths’, ‘Hindi’], :])
Or
print(Student1.iloc[[0, 3]])
(v)
print(Student1.loc[[‘Maths’, ‘Hindi’], [‘Ramit’, ‘Riya’]])

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 15. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write pandas code to do following:
(i) delete column ‘Riya’
(ii) delete columns ‘Arnab’ & ‘Mallika’
(iii) delete row ‘English’
(iv) delete rows ‘Maths’ & ‘Hindi’

Answer :
(i)
del Student1[‘Riya’]
Or
Student1.pop(‘Riya’)
Or
Student1 = Student1.drop(‘Riya’, axis=1)
(ii)
Student1 = Student1.drop([‘Arnab’, ‘Mallika’], axis=1)
Or
Student1 = Student1.drop([‘Arnab’, ‘Mallika’], axis=’columns’)
(iii)
Student1 = Student1.drop(‘English’)
Or
Student1 = Student1.drop(‘English’, axis=0)
(iv)
Student1 = Student1.drop([‘Maths’, ‘Hindi’])
Or
Student1 = Student1.drop([‘Maths’, ‘Hindi’], axis=0)
Or
Student1 = Student1.drop([‘Maths’, ‘Hindi’], axis=’index’)

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 16. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write output of following:
(i) print(Student1.loc['Maths' : 'English', :])
(ii) print(Student1.iloc[0 : 2, :])
Also justify your answer.

Answer :
(i)
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
(ii)
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
Justification :
DataFrame.loc[ ] is used for label based indexing of rows / columns
in DataFrames.
Syntax : loc[row_start : row_stop : row_step, col_start, col_end,
col_step]
DataFrame.iloc[ ] is used for position (integer) based indexing of
rows / columns in DataFrames.
Syntax : iloc[row_start : row_stop : row_step, col_start, col_end,
col_step]
When we use “iloc” for slicing, the value at the “row_stop / col_stop”
label / position is excluded.
If labelled “loc” for slicing, then value at the “row_stop / col_stop”
label / position is also included in the output.

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 17. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write output of following:
print(Student1.loc[[True, False, True, False]]
Justify your answer.

Answer :
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
English 97 96 88 67 99

Justification :
In DataFrames, Boolean values like True (1) and False (0) can be
associated with indices. They can also be used to filter the records
using the DataFrmae.loc[] method.
In order to select or omit particular row(s), we can use a Boolean
list specifying ‘True’ for the rows to be shown and ‘False’ for the
ones to be omitted in the output.

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 18. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write code to do the following:
(i) rename columns “Arnab” with “Aarti” and “Riya” with “Ram”
(ii) rename rows “Science” with “Sci” and “English” with “Eng”

Answer :
(i)
Student1 = Student1.rename({“Arnab” : “Aarti”, “Riya” : “Ram”},
axis=’columns’)
Or
Student1 = Student1.rename({“Arnab” : “Aarti”, “Riya” : “Ram”},
axis=1)
Or
Student1 = Student1.rename(columns={“Arnab” : “Aarti”, “Riya” :
“Ram”})
(ii)
Student1 = Student1.rename({“Arnab” : “Aarti”, “Riya” : “Ram”},
axis=’index’)
Or
Student1 = Student1.rename({“Arnab” : “Aarti”, “Riya” : “Ram”},
axis=0)
Or
Student1 = Student1.rename({“Arnab” : “Aarti”, “Riya” : “Ram”})
Or
Student1 = Student1.rename(index={“Arnab” : “Aarti”, “Riya” : “Ram”})

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 19. Consider the following dataframe “Df1” & “Df2”:
Df1 Df2
C1 C2 C1 C2
R1 1 2 R1 3 4
R2 5 6 R2 7 8
R3 9 10 R3 11 12
Write output of the following statements:
(i) print(Df1.append(Df2))
(ii) print(pd.concat([Df1, Df2], axis=1))
(ii) print(pd.concat([Df1, Df2]))

Answer :
(i)
C1 C2
R1 1 2
R2 5 6
R3 9 10
R1 3 4
R2 7 8
R3 11 12
(ii)
C1 C2 C1 C2
R1 1 2 3 4
R2 5 6 7 8
R3 9 10 11 12
(iii)
C1 C2
R1 1 2
R2 5 6
R3 9 10
R1 3 4
R2 7 8
R3 11 12

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 20. Write code to complete following for DataFrame “Df”:
i) to display row-index(axis labels) of the DataFrame
ii) to display a NumPy ndarray having all the values in the DataFrame,
without the axes labels
iii) to display a tuple representing the dimensionality of the
DataFrame
iv) to return the column-labels in DataFrame
v) to return the number of dimensions of the underlying data
vi) to return the number of elements/values in the underlying data
vii) to check if DataFrame is empty
(viii) to transpose the DataFrame. Means, row indices and column labels
of the DataFrame replace each other’s position
(ix) to display the first 3 rows in the DataFrame
(x) to display the last 3 rows in the DataFrame

Answer :
i) print(Df.index)
ii) print(Df.values)
iii) print(Df.shape)
iv) print(Df.columns)
v) print(Df.ndim)
vi) print(Df.size)
vii) print(Df.empty)
viii) print(Df.T)
ix) print(Df.head(3))
x) print(Df.tail(3))

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 21. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write output of the following code:
(i) print(Student1.sort_index())
(ii) print(Student1.sort_index(axis=1))
(iii) print(Student1.sort_index(axis=0, ascending=False))

Answer :
(i)
Arnab Ramit Samridhi Riya Mallika
English 97 96 88 67 99
Hindi 97 89 78 60 45
Maths 90 92 89 81 94
Science 91 81 91 71 95
(ii)
Arnab Mallika Ramit Riya Samridhi
Maths 90 94 92 81 89
Science 91 95 81 71 91
English 97 99 96 67 88
Hindi 97 45 89 60 78
(iii)
Arnab Ramit Samridhi Riya Mallika
Science 91 81 91 71 95
Maths 90 92 89 81 94
Hindi 97 89 78 60 45
English 97 96 88 67 99

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 22. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write output of the following code:
(i) print(Student1.sort_values('Ramit'))
(ii) print(Student1.sort_values('Ramit', axis=0, ascending=False))
(iii) print(Student1.sort_values(['Arnab', 'Ramit'], ascending =
[False, True]))

Answer :
(i)
Arnab Ramit Samridhi Riya Mallika
Science 91 81 91 71 95
Hindi 97 89 78 60 45
Maths 90 92 89 81 94
English 97 96 88 67 99
(ii)
Arnab Ramit Samridhi Riya Mallika
English 97 96 88 67 99
Maths 90 92 89 81 94
Hindi 97 89 78 60 45
Science 91 81 91 71 95
(iii)
Arnab Ramit Samridhi Riya Mallika
Hindi 97 89 78 60 45
English 97 96 88 67 99
Science 91 81 91 71 95
Maths 90 92 89 81 94

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 23. Consider the following dataframe “Student1”:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 97 96 88 67 99
Hindi 97 89 78 60 45
Write output of the following code:
(i) print(Student1.sum())
(ii) print(Student1.sum(axis=1))
(iii) print(Student1[['Arnab', 'Riya']].mean())

Answer :
(i)
Arnab 375
Ramit 358
Samridhi 346
Riya 279
Mallika 333
dtype: int64
(ii)
Maths 446
Science 429
English 447
Hindi 369
dtype: int64
(iii)
Arnab 93.75
Riya 69.75
dtype: float64

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 24. (i). Write code to read data from “mydata.csv” file into
DataFrame “Dfs”. Assume that csv file doesn’t contain column title.
Also read only 3 rows after skipping first 2 rows.
(ii). Also write date of DatafRame “Dfs” in new csv file “newDfs.csv”
without column labels and index of dataframe by using “;” as separator
into csv file.

Answer :
(i)
Dfs=pd.read_csv("mydata.csv", header= None, names= ["Rollno", "Name",
"Marks"), skiprows=2, nrows = 3)
(ii)
Dfs.to_csv( "newDfs.csv", index = False, header = False, sep = ';')

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 25. Draw the following bar graph representing the number of
students in each class.

Answer.
import matplotlib.pyplot as plt
Classes = ['VII', 'VIII', 'IX', 'X']
Students = [40, 45, 35, 44]
plt.bar(Classes, Students)
plt.title('Class-wise Number of Students')
plt.xlabel('Class')
plt.ylabel('Score[50]')
plt.ylim([30,50])
plt.show()

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 26. Draw the following horizontal bar graph representing performance
of students of a class.

Answer :
import matplotlib.pyplot as plt
val= [5, 25, 45, 20]
x = [1,2,3,4]
plt.barh(x, val, color= 'b')
plt.title('Bar Chart')
plt.ylabel('Roll Number')
plt.xlabel('Scores[50]')
plt.title('Performance Report')
plt.yticks([1,2,3,4])
plt.xticks([0,5,10,15,20,25,30,35,40,45,50])
plt.show()

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 27. Write a code to plot the sales of a product as shown in the
figure given below [Color of bars : blur, green, red]

Answer :
import pandas as pd
import matplotlib.pyplot as plt
V1=[14, 23, 49, 17]
V2=[15, 25, 45, 20]
V3=[16, 22, 47, 19]
X = pd.Series([1, 5, 9, 13])
plt.bar(X, V1, color = 'b')
plt.bar(X-1, V2, color = 'g')
plt.bar(X+1, V3, color = 'r')
plt.xticks([1, 5, 9, 13])
plt.title('Sales Report')
plt.ylabel(‘Sales’)
plt.xlim(-2, 15)
plt.ylim([10, 55])
plt.show()

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 28. Write a code to plot the speed of a passenger train as shown
in the figure given below:

Answer :
import pandas as pd
import matplotlib.pyplot as plt
Data= [[5, 25, 45, 20], [8, 13, 29, 27], [9, 29, 27, 39]]
X = pd.Series([0,1,2,3])
plt.plot(X, Data[0], color= 'b', label= 'Dayl')
plt.plot(X, Data [1], color = 'g', label = 'Day2' )
plt.plot(X, Data[2], color= 'r', label= 'Day3')
plt.legend( loc = 'upper left' )
plt.title( "Train's Speed Chart")
plt.xlabel('Check Points')
plt.ylabel('Speed')
plt.xticks([0,1,2,3])
plt.show()

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 29. Write a code to plot the speed of a passenger train as shown
in the figure given below:

Answer :
import pandas as pd
import matplotlib.pyplot as plt
data = {'Weight' : [60,61,63,65,61,60,47,89,52,58,50,47]}
df=pd.DataFrame(data)
df.plot(kind='hist', edgecolor='Green', linewidth=2, linestyle=':',
fill=False, hatch='o')
plt.show()

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 30. Write the output of the following SQL queries:
(i) SELECT POW(2,4);
(ii) SELECT POW(2,-2);
(iii) SELECT POW(-2,3);
(iv) SELECT ROUND(-1.23);
(v) SELECT ROUND(-1.58);
(vi) SELECT ROUND(1.43);
(vii) SELECT ROUND(6.298, 1);
(viii) SELECT ROUND(6.235, 0);
(ix) SELECT ROUND(56.235, -1);
(x) SELECT TRUNCATE(7.543,1);
(xi) SELECT TRUNCATE(4.567,0);
(xii) SELECT TRUNCATE(-7.45,1);
(xii) SELECT TRUNCATE(346,-2);
(xiv) SELECT MOD(11,4);

Answer :
(i) 16
(ii) 0.25
(iii) -8
(iv) -1
(v) -2
(vi) 1
(vii) 6.3
(viii) 6
(ix) 60
(x) 7.5
(xi) 4
(xii) -7.4
(xii) 300
(xiv) 3

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 31. Write the output of the following SQL queries:
(i) SELECT LENGTH ('Informatics');
(ii) SELECT CONCAT ('My', 'S', 'QL');
(iii) SELECT CONCAT('Class', NULL, 'XI');
(iv) SELECT INSTR ('Informatics', 'for');
(v) SELECT INSTR ('Computers', 'pet');
(vi) SELECT LOWER('INFORMATICS');
(vii) SELECT UPPER ('Informatics');
(viii) SELECT LEFT('Informatics', 3);
(ix) SELECT RIGHT('Informatics', 4);
(x) SELECT LTRIM(' Informatics');
(xi) SELECT RTRIM ('Informatics ');
(xii) SELECT TRIM(' Informatics ');
(xiii) SELECT SUBSTRING('Informatics',3);
(xiv) SELECT SUBSTRING('Informatics' FROM 4);
(xv) SELECT SUBSTRING('Informatics',3,4);
(xvi) SELECT SUBSTRING('Computers', -3);
(xvii) SELECT SUBSTRING('Computers', -5, 3);
(xviii) SELECT SUBSTRING('Computers' FROM -4FOR 2);
(xix) SELECT MID('Informatics',3,4);

Answer :
(i) 11
(ii) MySQL
(iii) NULL
(iv) 3
(v) 0
(vi) informatics
(vii) INFORMATICS
(viii) Inf
(ix) tics
(x) Informatics
(xi) Informatics
(xii) Informatics
(xiii) formatics
(xiv) ormatics
(xv) form
(xvi) ers
(xvii) ute
(xviii) te
(xix) form

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 32. Write the output of the following SQL queries:
(i) SELECT DATE('2010-02-26 01:02:03');
(ii) SELECT MONTH('2010-02-26');
(iii) SELECT YEAR('2010-02-26');
(iv) SELECT DAYOFMONTH('2009-07-21');
(v) SELECT DAY('2009-07-21');
(vi) SELECT DAYOFYEAR('2009-02-01');
(vii) SELECT MONTHNAME('2009-07-21');

Answer :
(i) 2010-02-26
(ii) 2
(iii) 2010
(iv) 21
(v) 21
(vi) 32
(vii) JULY

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 33. Consider the table "Grocer" and write SQL queries for the tasks
that follow:
Table: Grocer
Item_Id ItemName UnitPrice Quantity(kg) Date_Purchase
1 Rice 52.50 80 2010-02-01
2 Wheat 25.40 50 2010-03-09
3 Corn 50.80 100 2010-03-11
4 Semolina 28.90 50 2010-01-15
(Unit Price is per kg price)
I. Display Item name, unit price along with Date of purchase for all
the Items.
II. Display Item name along with Month (in number) when it was
purchased for all the items.
III. Display Item name along with year in which it was purchased for
all the items.
IV. Display Item Id, Date of Purchase and day name of week (e.g.
Monday) on which it was purchased for all the items.
V. Display names of all the items that were purchased on Mondays or
Tuesdays.
VI. Display the day name of the week on which Rice was purchased.
VII. Display the Item name and unit price truncated to integer value
(no decimal digits)of all the items.
VIII. Display current date

Answer :
i. select item_name, unitprice, date_purchase from grocer;
ii. select item_name, month(date_purchase) from grocer;
iii. select item_name, year(date_purchase) from grocer;
iv. select item_name, unitprice, date_purchase,
dayname(date_purchase) from grocer;
v. select item_name from groces where dayname(date_purchase) in
('monday', 'tuesday');
vi. select dayname(date_purchase) from grocer where
item_name='rice';
vi. select item_name, round(unitprice) from grocer;
viii. select curdate();

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 34. Write SQL queries for the tasks that follow:
Table: Charity
P_Id LastName FirstName Address City Contri
1 Bindra Jaspreet 5B, Gomti Nagar Lucknow 3500.50
2 Rana Monica 21A, Bandra Mumbai 2768.00
3 Singh Jatinder 8, Punjabi Bagh Delhi 2000.50
4 Arora Satinder K/1, Shere Punjab Colony Mumbai 1900.00
5 Krishnan Vineeta A-75, Adarsh Nagar Jaipur 3700.00
(Contribution (contri) is in Rs.)
I. Display all first names in lowercase
II. Display all last names of people of Mumbai city in uppercase
III. Display Person Id along with First 3 characters of his/her name.
IV. Display first name concatenated with last name for all the
employees.
V. Display length of address along with Person Id
VI. Display last 2 characters of City and Person ID.
VII. Display Last Names and First names of people who have "at" in the
second or third position in their first names.
VIII. Display the position of 'a' in Last name in every row.
IX. Display Last Name and First name of people who have "a" as the
last character in their First names.
X. Display the first name and last name concatenated after removing
the leading and trailing blanks.
XI. Display Person Id, last names and contribution (contri) rounded
to the nearest rupee of all the persons.
XII. Display Person Id, last name and contribution with decimal digits
truncated of all the persons.
XIII. Display Last name, contribution and a third column which has
contribution divided by 10. Round it to two decimal points.

Answer :
i. select lcase(firstname) from charity;
ii. select ucase(firstname) from charity where city='mumbai';
iii. select p_id, left(firstname, 3) from charity;
iv. select concat(firstname, ' ' ,lastname) from charity;
v. select length(address), p_id from charity;
vi. select right(city,2), p_id from charity;
vii. select lastname, firstname fromcharity where mid(firstname,
2,2)='at';
viii. select lastname, instr(lastname, 'a') from charity;
ix. select lastname, firstname from charity where right(firstname,
1)='a';
x. select concat(trim(firstname),trim(lastname)) from charity;
xi. select p_id, lastname, round(contribution) from charity;
xii. select p_id, lastname, truncate(contribution, 0) from charity;
xiii. select lastname, round(contribution/10, 2) from charity;

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 35. Consider the following tables Employee and Department.
Table : Employee
ECode LastName FirstName Department
101 Sharma Amit Sales
102 Arora Shiv Personnel
103 Lakshmi KS Accounts
104 Rajlani Shivika Accounts
105 Thakral Satvik Sales
Write SQL statements to do the following:
a) Display the last names and first names of all employees.
b) Display the Department names of all employees, without duplicates.
c) Display all the details of employees with last name as "Lakshmi".
d) Display all the details of employees whose last name is "Rajlani"
or "Sharma".
e) Display the codes and first names of all employees of 'Accounts'
department.
F) Display all the details of employees whose First name begins with
"S".

Answer :
(A) SELECT LASTNAME, FIRSTNAME FROM EMPLOYEE;
(B) SELECT DISTINCT(DEPARTMENT) FROM EMPLOYEE;
(C) SELECT * FROM EMPLOYEE WHERE LASTNAME = ‘LAKSHMI’;
(D) SELECT * FROM EMPLOYEE WHERE LASTNAME = ‘RAJLAXMI’ OR
LASTNAME=’SHARMA’;
(E) SELECT ECODE, FIRSTNAME FROM EMPLOYEE WHERE DEPARTMENT =
‘ACCOUNTS’;
(F) SELECT * FROM EMPLOYEE WHERE FIRSTNAME LIKE ‘S%’;

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 36. Write the output produced by the following SQL commands:
a. SELECT POW(4,3), POW(3,4);
b. SELECT ROUND(543.5694,2), ROUND(543.5694), ROUND(543.5694,-1);
c. SELECT TRUNCATE(543.5694,2), TRUNCATE(543.5694,-1);
d. SELECT LENGTH("Prof. M. L. Sharma");
e. SELECT CONCAT("SHEIKH", " HAROON") "FULL NAME";
f. SELECT LEFT("Unicode",3), RIGHT("Unicode",4);
g. SELECT INSTR("UNICODE","CO"), INSTR("UNICODE","CD");
h. SELECT MID("Informatics",3,4), SUBSTR("Practices",3);

Answer :
a.
+----------+----------+
| POW(4,3) | POW(3,4) |
+----------+----------+
| 64 | 81 |
+----------+----------+
b.
+-------------------+-----------------+--------------------+
| ROUND(543.5694,2) | ROUND(543.5694) | ROUND(543.5694,-1) |
+-------------------+-----------------+--------------------+
| 543.57 | 544 | 540 |
+-------------------+-----------------+--------------------+
c.
+----------------------+-----------------------+
| TRUNCATE(543.5694,2) | TRUNCATE(543.5694,-1) |
+----------------------+-----------------------+
| 543.56 | 540 |
+----------------------+-----------------------+
d.
+------------------------------+
| LENGTH("Prof. M. L. Sharma") |
+------------------------------+
| 18 |
+------------------------------+
e.
+---------------+
| FULL NAME |
+---------------+
| SHEIKH HAROON |
+---------------+
f.
+-------------------+--------------------+
| LEFT("Unicode",3) | RIGHT("Unicode",4) |
+-------------------+--------------------+
| Uni | code |
+-------------------+--------------------+
Manish Kumar Sharma – IP – Practical File
Manish Kumar Sharma – IP – Practical File
g.
+-----------------------+-----------------------+
| INSTR("UNICODE","CO") | INSTR("UNICODE","CD") |
+-----------------------+-----------------------+
| 4 | 0 |
+-----------------------+-----------------------+
h.
+------------------------+-----------------------+
| MID("Informatics",3,4) | SUBSTR("Practices",3) |
+------------------------+-----------------------+
| form | actices |
+------------------------+-----------------------+

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 37. Give the output for following SQL queries as per given table
“LAB”:

NO ITEMNAME COSTPERITEM QTY DATEPURCHASE WARRANTY OPERATIONAL

1 Computer 60000 10 1996/05/21 2 7


2 Printer 15000 2 1997/05/21 4 2
3 Scanner 18000 1 1998/08/29 3 1
4 Camera 19000 10 1996/06/13 1 2
5 Hub 8000 2 1999/10/31 2 1
6 UPS 5000 10 1996/05/21 1 4
7 Plotter 25000 1 2000/01/11 2 2

(i) SELECT MIN(DISTINCT Qty) FROM LABORATORY;


(ii) SELECT MAX(Warranty) FROM LAB WHERE Qty = 2;
(iii) SELECT SUM(CostPerItem) FROM LAB WHERE Qty > 2;
(iv) SELECT AVG(CostPerItem) FROM LAB WHERE DateofPurchase <
‘1997/01/01’;

Answer :
(i)
MIN(DISTINCT Qty)
1
(ii)
MAX(Warranty)
4
(iii)
SUM(CostPerItem)
84000
(iv)
AVG(CostPerItem)
28000

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 38. In a database create the following tables with suitable
constraints:
Table : ITEMS
I_Code Name Category Rate
1001 Masala Dosa South Indian 60
1002 Vada Sambhar South Indian 40
1003 Idli Sambhar South Indian 40
2001 Chow Mein Chinese 80
2002 Dimsum Chinese 60
2003 Soup Chinese 50
3001 Pizza Italian 240
3002 Pasta Italian 125
Table : BILLS
BillNo Date I_Code qty
1 2010-04-01 1002 2
1 2010-04-01 3001 1
2 2010-04-01 1001 3
2 2010-04-01 1002 1
2 2010-04-01 2003 2
3 2010-04-02 2002 1
4 2010-04-02 2002 4
4 2010-04-02 2003 2
5 2010-04-03 2003 2
5 2010-04-03 3001 1
5 2010-04-03 3002 3
Based on these tables write SQL statements for the following queries:
i. Display the average rate of a South Indian item.
ii. Display the number of items in each category.
iii. Display the total quantity sold for each item code.
iv. Display total quantity of each item sold but don't display this
data for the items whose total quantity sold is less than 3.
v. Display the bill records for each Italian item sold.
vi. Display the total value of items sold for each bill.
b) Identify the Foreign Keys (if any) of these tables. Justify your
answer.
Answer :
i. select * from items where category = ‘south indian’;
ii. select category, count(i_code) from items group by category;
iii. select i_code, sum(qty) from bills group by i_code;
iv. select i_code, sum(qty) from bills group by i_code having sum(qty)
> 3;
v. Select Bills.* from Items, Bills where Items.I_code =
Bills.I_code and Items.Category = ‘Italian’;
vi. Select B.I_Code, sum(B.Qty * I.Rate) as ‘Total’ from Items I,
Bills B Where I.I_code = B.I_code group by B.I_Code;

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
(b) Bills.I_Code. It is originally column of ‘Items’ table and we
kept it in ‘Bills’ table so that we can get related records after
joining these tables. In items

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
Q 39. Table : STUDENTS
AdmNo Name Class Sec RNo Address Phone
1271 Utkarsh Madaan 12 C 1 C-32, Punjabi 01412356154
Bagh
1324 Naresh Sharma 10 A 1 31, Mohan Nagar 01413115654
1325 Md. Yusuf 10 A 2 12/21, Chand 01412115654
Nagar
1328 Sumedha 10 B 23 59, Moti Nagar 01413565412
1364 Subya Akhtar 11 B 13 12, Janak Puri NULL
1434 Varuna 12 B 21 69, Rohini NULL
1461 David DSouza 11 B 1 D-34, Model Town 0141243554
2324 Satinder Singh 12 C 1 1/2, Gulmohar 0141233654
Park
2328 Peter Jones 10 A 18 21/32B, Vishal 01412356154
Enclave
2371 Mohini Mehta 11 C 12 37, Raja Garden 01412135654
Table : SPORTS
AdmNo Game CoachName Grade
1324 Cricket Narendra A
1364 Volleball M.P. Singh A
1271 Volleball M.P. Singh B
1434 Basket Ball I. Malhotra B
1461 Cricket Narendra B
2328 Basket Ball I. Malhotra A
2371 Basket Ball I. Malhotra A
1271 Basket Ball I. Malhotra A
1434 Cricket Narendra A
2328 Cricket Narendra B
1364 Basket Ball I. Malhotra B
a) Based on these tables write SQL statements for the following
queries:
i. Display the lowest and the highest classes from the table STUDENTS.
ii. Display the number of students in each class from the table
STUDENTS.
iii. Display the number of students in class 10.
iv. Display al details of student who play cricket.
v. Display name and phone of students whose coach is ‘Narendra’ and
grade id ‘A’;
vi. Display the Number of students with each coach.
vii. Display admno, name, class, sec, and rno of students who secured
grade ‘A’.
b) Identify the Foreign Keys (if any) of these tables. Justify your
choices.
Answer : (a)
i. select max(class), min(class) from students;
ii. select class, count(admno) from students group by class;
iii. select class, count(admno) from students where class=10;

Manish Kumar Sharma – IP – Practical File


Manish Kumar Sharma – IP – Practical File
iv. select students.* from students, sports where
students.admno=sports.admno and sports.game='cricket';
v. select students.name, students.phone from students, sports where
students.admno=sports.admno and sports.grade='A' and
sports.coachname='narendra';
vi. select coachname, count(admno) from sports group by coachname;
vii. select students.admno, students.name, students.class,
students.sec, students.rno from students, sports where
students.admno=sports.admno and sports.grade='A';
(b). Sports - Admno. Primary key of a table if exits in second table
is known as foreign key in second table. Primary key contains unique
values whereas in foreign key column we can pass any value of primary
key as well as we can repeat a value.

Manish Kumar Sharma – IP – Practical File

You might also like