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']])
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
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.
Related questions:
2026: 23 May Shift 2
2026: 26 May Shift 1
2025: 30 May Shift 2
2026: 24 May Shift 1