Pandas DataFrame - Select even indexed rows
Pandas DataFrame - Select even indexed rows
In Pandas DataFrame, you can select even indexed rows using iloc property of the DataFrame and slicing technique. iloc provides integer based indexing for selecting the rows. And using slicing technique, you can select the even indexed rows.
In this tutorial, we shall see the syntax of the expression to select even indexed rows using iloc property, and an example with detailed steps and program.
Syntax to select even indexed rows in DataFrame
The syntax of the expression using iloc property with slice expression on the given DataFrame df to select even indexed rows is
df.iloc[::2]
There are three positions in the square brackets that create the slice.
[start:stop:step]
start
The integer index of a DataFrame starts from 0. We need even indexed rows and the even numbers start from 0. The default value of start, which is the beginning of the integer index 0 would suffice. Therefore start is not mentioned, and the default value of 0 will take effect.
stop
We need to select the even indexed rows till the end of the DataFrame. The default value of stop is the end of the DataFrame. Therefore stop is also not mentioned, and the default value will take effect.
step
For even numbers, the step value is 2. This selects alternative rows.
Starting at default index value of 0, in steps of 2, till the end of the DataFrame. This slice expression selects the rows at even indices of the DataFrame.
1. Select even indexed rows from DataFrame using iloc and slicing
In this example, we are given a DataFrame in df, and we need to select rows at even indices using iloc property of the DataFrame.
Steps
- Import pandas library.
import pandas as pd
- Given DataFrame in df.
df = pd.DataFrame({
'name': ['apple', 'banana', 'cherry', 'fig', 'mango', 'pear'],
'quantity': [14, 0, 0, 37, 25, 80]
})
- Use iloc property and slice expression to selected rows at even indices.
df.iloc[::2]
- The above expression returns a new DataFrame with the rows at even indices from original DataFrame. Store the returned DataFrame in a variable, say df_even_rows, and print it to output.
Program
The complete program to select rows from a DataFrame whose index is an even number, is given below.
Python Program
import pandas as pd
# Take a DataFrame
df = pd.DataFrame({
'name': ['apple', 'banana', 'cherry', 'fig', 'mango', 'pear'],
'quantity': [14, 0, 0, 37, 25, 80]
})
# Select rows whose index is even
df_even_rows = df.iloc[::2]
# Print DataFrame
print(f"Original DataFrame\n{df}\n")
print(f"Rows at even index\n{df_even_rows}")
Output
Original DataFrame
name quantity
0 apple 14
1 banana 0
2 cherry 0
3 fig 37
4 mango 25
5 pear 80
Rows at even index
name quantity
0 apple 14
2 cherry 0
4 mango 25
Summary
In this Pandas Tutorial, we learned how to select even indexed rows from a DataFrame using iloc property of the DataFrame and slicing technique.