Skip to main contentSkip to solution

What will be the output of the following code?

import pandas as pd

data={'name': pd.Series(['Ashu','Arun','Ashi']),

'age':pd.Series([25,30,22]),

'gender':pd.Series(['M','M','F'])}

df = pd.DataFrame(data)

print(df.loc[0:1,['name','age']])

Solution

✅ Correct Option: 1

loc selects by label, and a slice in loc includes both ends. So 0:1 picks the rows labelled 0 and 1, which are the first two rows. The list ['name','age'] then keeps only those two columns.

Output:

   name  age
0  Ashu   25
1  Arun   30

Option 3: name and age are the first two columns, but the output shows only two of the three rows, not the full columns.

Option 2: the last two rows would be labels 1 and 2, which needs loc[1:2].

Option 4: the last two columns would be age and gender.

With iloc, the end of a slice is excluded, but with loc it is included.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question