Skip to main content

Python Pandas Select Every Nth Row In DataFrame (Example)

Selecting every nth row from the dataframe.
We can select every nth row item from the pandas dataframe by using ".iloc" method. It has the slicing features and stepping features similar to list slicing.
iloc is index based and starts from zero


Creating a new dataframe with dictionary 


# importing pandas
import pandas as pd


# animal_data_
animal_data_ext = {
    "Name": ["Cat", "Dog", "Cow","Tiger","Goat","Snake"],
    "Sound": ["Meow", "Woof", "Mooo","Rwaar","Baaa","Skkksss"],
}

#creating a dataframe using the animal_data_ext dictionary
animal_ext_df = pd.DataFrame(animal_data_ext)

#printing animal_ext_df
print("animal_ext_df \n", animal_ext_df)

animal_ext_df Name Sound 0 Cat Meow 1 Dog Woof 2 Cow Mooo 3 Tiger Rwaar 4 Goat Baaa 5 Snake Skkksss


Selecting every nth row (including the first row in the dataframe)


#nth row number
nth_num = 2

#select every nth row number - including first row in the dataframe
#using steps
every_nth_row = animal_ext_df.iloc[::nth_num]

print("every_nth_row including first row \n", every_nth_row)

every_nth_row including first row Name Sound 0 Cat Meow 2 Cow Mooo 4 Goat Baaa



Selecting every nth row (excluding the first row in the dataframe)


#nth row number
nth_num = 2

#select every nth row number - excluding first row in the dataframe
every_nth_row = animal_ext_df.iloc[nth_num::nth_num]

print("every_nth_row excluding first row \n", every_nth_row)

every_nth_row excluding first row Name Sound 2 Cow Mooo 4 Goat Baaa

Comments

Topics

Show more