CBSE Class 12 Informatics Practices Question 138 of 167

Python Pandas — I — Question 28

Back to all questions
28
Question

Question 22

Assume that required libraries (panda and numpy) are imported and dataframe df2 has been created as per questions 17 and 18 above. Predict the output produced by following code fragment :

print(df2.loc["Jiya"])
print(df2.loc["Jiya", "IQ"])
print(df2.loc["Jiya":"Tim", "IQ":"College"]) 
print(df2.iloc[0])
print(df2.iloc[0, 5])
print(df2.iloc[0:2, 5:8])
Answer
Output
name        Jiya
age           10
weight        75
height       4.5
siblings       1
gender         M
IQ           130
College      NaN
Name: Jiya, dtype: object
130
       IQ College
Jiya  130     NaN
Tim   105     NaN
name        Jiya
age           10
weight        75
height       4.5
siblings       1
gender         M
IQ           130
College      NaN
Name: Jiya, dtype: object
M
     gender   IQ College
Jiya      M  130     NaN
Tim       M  105     NaN
Explanation
  1. print(df2.loc["Jiya"]) — This line prints all columns of the row with the index "Jiya".
  2. print(df2.loc["Jiya", "IQ"]) — This line prints the value of the "IQ" column for the row with the index "Jiya".
  3. print(df2.loc["Jiya":"Tim", "IQ":"College"]) — This line prints a subset of rows and columns using labels, from "Jiya" to "Tim" for rows and from "IQ" to "College" for columns.
  4. print(df2.iloc[0]) — This line prints all columns of the first row using integer-based indexing (position 0).
  5. print(df2.iloc[0, 5]) — This line prints the value of the 6th column for the first row using integer-based indexing.
  6. print(df2.iloc[0:2, 5:8]) — This line prints a subset of rows and columns using integer-based indexing, selecting rows from position 0 to 1 and columns from position 5 to 7.