![]() |
VOOZH | about |
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.
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.
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.
Output
Name Karan
Age 30
Department Finance
Salary 55000
Name: 2, dtype: object
Explanation: The : selects all columns of row index 2.
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.
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.
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.