When using iloc to select ranges of Pandas dataframe rows, can we skip rows?


#1

Question

When using iloc to select ranges of Pandas dataframe rows, can we skip rows? For instance, can we choose to select every second or third row only?

Answer

You can! Selecting multiple rows using .iloc is very similar to list slicing in Python. There are a few ways to select rows using iloc.

To select just a single row, we pass in a single value, the index. For example with Python lists,
numbers[0] # First element of numbers list

And with Dataframes, we would do something similar,
orders.iloc[0].

Selecting a range of elements of a list and a range of rows in Pandas is also very similar.

# Python list
numbers[3:7]

# Pandas
orders.iloc[3:7]

To skip a certain number of indexes per index, we can include a third, step, value.

# This selects values at indexes 0, 3, 6, 9.
# Python list
numbers[0:10:3]

# This selects rows at indexes 0, 3, 6, 9
# Pandas
orders.iloc[0:10:3]