Get Top & Bottom N Rows of pandas DataFrame in Python (2 Examples)

In this tutorial you’ll learn how to get the top and bottom N rows of a pandas DataFrame in the Python programming language.

Setting up the Examples

import pandas as pd                                   # Import pandas library in Python
my_df = pd.DataFrame({'A':[5, 1, 5, 5, 1, 2, 8, 2],  # Construct example DataFrame in Python
                      'B':['b', 'x', 'a', 'a', 'a', 'c', 'x', 'b'],
                      'C':['a', 'a', 'c', 's', 'b', 'a', 'f', 'c']})
print(my_df)                                         # Display example DataFrame in console
#    A  B  C
# 0  5  b  a
# 1  1  x  a
# 2  5  a  c
# 3  5  a  s
# 4  1  a  b
# 5  2  c  a
# 6  8  x  f
# 7  2  b  c

Example 1: Extracting Upper N Rows of pandas DataFrame

print(my_df.head(3))                                 # Return head of example data
#    A  B  C
# 0  5  b  a
# 1  1  x  a
# 2  5  a  c

Example 2: Extracting Lower N Rows of pandas DataFrame

print(my_df.tail(3))                                 # Return tail of example data
#    A  B  C
# 5  2  c  a
# 6  8  x  f
# 7  2  b  c

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top