![]() |
VOOZH | about |
Selecting rows by integer position means retrieving one or more rows using their numeric (0-based) index. In this article we show two methods to do that: iloc[] and iat[], with short examples for each.
The iloc[] method in Pandas is used to access rows and columns based on their integer position. It can return an entire row, a slice of rows or specific row-column combinations.
Example 1: This example shows how to iterate over a DataFrame and convert each row into a list using iloc[].
[[10000, '10/2/2011', 'Music'], [5000, '11/2/2011', 'Poetry'], [15000, '12/2/2011', 'Theatre']]
Explanation: Here, iloc[i, :] retrieves all columns of row i. Each row is converted into a list and stored in rows.
Example 2: This example extracts the second row of the same DataFrame.
Output
Date 11/2/2011
Event Poetry
Cost 5000
Name: 1, dtype: object
Explanation: The code uses iloc[1] to fetch the row at index 1. It returns a Pandas Series representing that row.
The iat[] method provides fast access to individual values using row and column indices. By looping through columns, it can be used to extract entire rows as lists.
Example 1: This example builds each row by iterating column indices with iat[].
Output
[['10/2/2011', 'Music', 10000], ['11/2/2011', 'Poetry', 5000], ['12/2/2011', 'Theatre', 15000]]
Explanation: For each row index i, the code iterates over all column indices j and fetches values with iat[i, j]. Each row is stored as a list.
Example 2: This example extracts the values of the third row from the same DataFrame.
Output
['12/2/2011', 'Theatre', 15000]
Explanation: By looping through all columns of row index 2, all cell values are collected into a list.