Pandas DataFrame – Select every nth row

Pandas DataFrame – Select every nth row

In Pandas DataFrame, you can select every nth row 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 every nth row.

In this tutorial, we shall see the syntax of the expression to select every nth row using iloc property, and an example with detailed steps and program.

Syntax to select every nth row in DataFrame

The syntax of the expression to select every nth row using slice expression on the iloc property of given DataFrame df is

df.iloc[::n]

There are three positions in the square brackets that create the slice.

[start:stop:step]

Starting at index value of 0 (default start value), in steps of n (step=n), till the end (default stop value) of the DataFrame. This slice expression selects the rows in the DataFrame in the intervals specified by n.

1. Select rows at 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

  1. Import pandas library.
import pandas as pd
  1. Given DataFrame in df.
df = pd.DataFrame({
    'A': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
})
  1. Given integer value in n.
n = 3
  1. Use iloc property and slice expression to select every nth row in the DataFrame df.
df.iloc[::n]
  1. The above expression returns a new DataFrame with the rows at intervals of n from original DataFrame. Store the returned DataFrame in a variable, say df_nth_rows, and print it to output.

Program

The complete program to select every nth row from a DataFrame, is given below.

Python Program

import pandas as pd

# Take a DataFrame
df = pd.DataFrame({
    'A': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
})

# Internal n
n = 3

# Select every nth row
df_nth_rows = df.iloc[::3]

# Print DataFrame
print(f"Original DataFrame\n{df}\n")
print(f"Rows every nth row\n{df_nth_rows}")
Run Code Copy

Output

Original DataFrame
     A
0   10
1   20
2   30
3   40
4   50
5   60
6   70
7   80
8   90
9  100

Rows every nth row
     A
0   10
3   40
6   70
9  100

Summary

In this Pandas Tutorial, we learned how to select every nth row from a DataFrame using iloc property of the DataFrame and slicing technique.

Related Tutorials

Code copied to clipboard successfully 👍