Selecting specific rows using numeric positions allows you to retrieve one or more rows based on their 0-based index. In this article, we demonstrate two methods to do this in Pandas: iloc[] and iat[], with concise examples for each.
Using loc[]
The loc[] method selects rows and columns based on labels (row index and column names).
Example 1: In this example, we select rows 1 to 3 and only the columns Name and Department.
import pandas as pd
data = {'Name': ['Amit', 'Riya', 'Karan', 'Neha', 'Arjun'],
'Age': [28, 24, 30, 26, 29],
'Department': ['HR', 'IT', 'Finance', 'Marketing', 'Sales'],
'Salary': [50000, 60000, 55000, 65000, 70000] }
df = pd.DataFrame(data)
print(df.loc[1:3, ['Name', 'Department']])
Output
Name Department 1 Riya IT 2 Karan Finance 3 Neha Marketing
Explanation: Here df.loc[1:3, ['Name','Department']] fetches rows 1 to 3 and only the selected columns.
Example 2: This program retrieves the row at index 2 with all its column values.
print(df.loc[2, :])
Output
Name Karan
Age 30
Department Finance
Salary 55000
Name: 2, dtype: object
Explanation: The : selects all columns of row index 2.
Using iloc[]
The iloc[] method selects rows and columns based on integer positions.
Example 1: In this example, we select the first three rows and columns at positions 0 and 2.
print(df.iloc[0:3, [0, 2]])
Output
Name Department
0 Amit HR
1 Riya IT
2 Karan Finance
Explanation: The code picks rows 0-2 and only the first (Name) and third (Department) columns.
Example 2: This code selects rows at positions 1 and 4 with columns at positions 1 and 3.
print(df.iloc[[1, 4], [1, 3]])
Output
Age Salary
1 24 60000
4 29 70000
Explanation: iloc[[1,4], [1,3]] fetches row 1 and 4 and columns Age and Salary.