Pandas DataFrame - Select odd indexed rows
Pandas DataFrame - Select odd indexed rows
In Pandas DataFrame, you can select odd 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 odd indexed rows.
In this tutorial, we shall see the syntax of the expression to select odd indexed rows using iloc property, and an example with detailed steps and program.
Syntax to select odd indexed rows in DataFrame
The syntax of the expression using iloc property with slice expression on the given DataFrame df to select odd indexed rows is
df.iloc[1::2]
There are three positions in the square brackets that create the slice.
[start:stop:step]
Starting at index value of 1 (start=1), in steps of 2 (step=2), till the end (stop is left blank) of the DataFrame. This slice expression selects the rows at odd indices of the DataFrame.
1. Select odd 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 odd 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 odd indices.
df.iloc[1::2]
- The above expression returns a new DataFrame with the rows at odd indices from original DataFrame. Store the returned DataFrame in a variable, say df_odd_rows, and print it to output.
Program
The complete program to select rows from a DataFrame whose index is an odd 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 odd
df_odd_rows = df.iloc[1::2]
# Print DataFrame
print(f"Original DataFrame\n{df}\n")
print(f"Rows at odd index\n{df_odd_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 odd index
name quantity
1 banana 0
3 fig 37
5 pear 80
Summary
In this Pandas Tutorial, we learned how to select odd indexed rows from a DataFrame using iloc property of the DataFrame and slicing technique.