Pandas DataFrame - Select row by index
Pandas DataFrame - Select row by index
To select a row by index in a DataFrame in Pandas, you can use iloc property of the DataFrame object. Read iloc property of the given DataFrame, and specify the index of the required row in the square brackets.
The syntax to use iloc property of the DataFrame to get the row at specified index is
dataframe.iloc[index]
For example, if you would like to select second row, whose index is 1, then use the following expression.
dataframe.iloc[1]
In this tutorial, we will go through some examples, with step by step explanation of how to select a row by index in a DataFrame using iloc property.
Example
1. Select row at index=1 in DataFrame
In this example, we are given a DataFrame in df_input with five rows. We have to select the row at index=1 in the DataFrame.
Steps
- Given a DataFrame in df_input with three columns 'A', 'B', and 'C', and five rows.
df_input = pd.DataFrame({
'A': [2, 4, 6, 8, 10],
'B': [1, 3, 5, 7, 9],
'C': [10, 20, 30, 40, 50]})
- Read iloc property of the DataFrame and specify the index value of 1 inside the square brackets.
df_input.iloc[1]
- The above expression returns a Series object. You may store it in a variable and print it to output.
second_row = df_input.iloc[1]
- If you would like the row as a list or dictionary, you can call respective method on the row second_row.
print(second_row.to_dict())
print(second_row.tolist())
Program
The complete program to select a row by index in a given DataFrame.
Python Program
import pandas as pd
# Take a DataFrame
df_input = pd.DataFrame({
'A': [2, 4, 6, 8, 10],
'B': [1, 3, 5, 7, 9],
'C': [10, 20, 30, 40, 50]})
# Select row by index
second_row = df_input.iloc[1]
print(second_row)
Output
A 4
B 3
C 20
Name: 1, dtype: int64
You may convert it to a list using tolist() method, as shown in the following program.
Python Program
import pandas as pd
# Take a DataFrame
df_input = pd.DataFrame({
'A': [2, 4, 6, 8, 10],
'B': [1, 3, 5, 7, 9],
'C': [10, 20, 30, 40, 50]})
# Select row by index
second_row = df_input.iloc[1]
print(second_row.tolist())
Output
[4, 3, 20]
Summary
In this Pandas Tutorial, we learned how to select a row by index in a DataFrame using iloc property, with examples.