Order pandas DataFrame Rows by Index in Python (Example Code)

In this post you’ll learn how to order the rows of a pandas DataFrame by index in the Python programming language.

Preparing the Example

import pandas as pd                         # Import pandas library to Python
my_df = pd.DataFrame({'A':range(20, 24),    # Construct pandas DataFrame
                      'B':range(10, 6, - 1)},
                     index = [50, 1, 99, 13])
print(my_df)
#      A   B
# 50  20  10
# 1   21   9
# 99  22   8
# 13  23   7

Example: Apply sort_sindex Function to Order Rows of pandas DataFrame

my_df = my_df.sort_index()                  # Ordering rows by index
print(my_df)
#      A   B
# 1   21   9
# 13  23   7
# 50  20  10
# 99  22   8

Related Articles & Further Resources

Have a look at the following list of Python programming tutorials. They explain topics such as indices, naming data, and data inspection.

Leave a Reply

Your email address will not be published. Required fields are marked *

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