Search code snippets, questions, articles...

Pandas - Change rows order of a DataFrame using index list

Sorting or reordering Dataframe rows is quite a common operation. DataFrame provides the sort method for that, but this method sorts a DataFrame based on the values in its columns. In this post, we will reorder the rows based on the index list.
import pandas as pd

# create a dictionary
students = {
  "name": ["Tom", "John", "Rick", "Sneha", "Johnson"],
  "score": [90, 80, 98, 99, 82],
  "subjects": ["Math", "Physics", "Chemistry", "english", "Data Structure"]
}

# create the dataframe from dictionary
df = pd.DataFrame(students, index=['a', 'b', 'c', 'd', 'e'])
print(df)

#change rows orders using index list
df = df.reindex(['d', 'a', 'e', 'b', 'c'])
print(df)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

+----+---------+---------+----------------+
|    | name    |   score | subjects       |
|----+---------+---------+----------------|
| a  | Tom     |      90 | Math           |
| b  | John    |      80 | Physics        |
| c  | Rick    |      98 | Chemistry      |
| d  | Sneha   |      99 | english        |
| e  | Johnson |      82 | Data Structure |
+----+---------+---------+----------------+


+----+---------+---------+----------------+
|    | name    |   score | subjects       |
|----+---------+---------+----------------|
| d  | Sneha   |      99 | english        |
| a  | Tom     |      90 | Math           |
| e  | Johnson |      82 | Data Structure |
| b  | John    |      80 | Physics        |
| c  | Rick    |      98 | Chemistry      |
+----+---------+---------+----------------+

If you are using the Pandas library in your Python project then you must be using DataFrames to perform specific tasks on large data. You can sort columns and rows by value using the sort() function. But sometimes it is required to change the orders of rows using the DataFrame index. We can arrange them in ascending and descending order easily but if you want to sort them using a Python List that contains the indexes of Dataframe as its items. We use DataFrame.reindex() function to reorder the rows using the index list.

Explanation of the above code example

1. Created a dictionary named students that contains multiple key-value pairs. We will be using keys as column names and values as rows of Dataframe. The values in the student's dictionary are in the form of a List.

2. Created a DataFrame from the above dictionary.  We are also assigning custom indexes to the DataFrame. We are using the below code syntax to do that. 

df = pd.DataFrame(students, index=['a', 'b', 'c', 'd', 'e'])

3. Using reindex() function of Pandas Dataframe to change the order of rows. 

df.reindex(['d', 'a', 'e', 'b', 'c'])
Was this helpful?
0 Comments