Reorder indexed rows based on a list in Pandas DataFrame – Python
When you want to modify or reorder the index of rows, it becomes easy by doing with the Pandas DataFrame. Pandas is a DataFrame in Python programming which is a two-dimensional data structure consisting of three components, columns, rows, and data. So, in this tutorial, we will learn about how to reorder indexed rows based on a list in Pandas DataFrame.
Let us take an example to proceed with this method. So read this tutorial very carefully and enjoy the session of coding in Python.
The first step in this method is to import the Pandas module using the command prompt. Secondly, create the dictionary, fill the required data, and print the original DataFrame. Then the next step is to change the order of the rows using an index list(you can change the indexes according to you)which will be made from default indexes or the indexes which were made earlier and at last print the reordered DataFrame.
Refer to the code given below to clear your concepts regarding this method of Pandas DataFrame in Python.
#import the pandas module import pandas as pd # creating a dictionary students = { "name": ["Sush", "John", "Rick", "Kush", "Ipshita"], "marks": [90, 80, 98, 99, 92], "subjects": ["Math", "Physics", "Chemistry", "English", "Computer"] } df = pd.DataFrame(students) print("The Original DataFrame") print(df) #Reordering using Pandas dataframe made from default index df = df.reindex([4, 2, 1, 3, 2]) print("After
Output:
The Original DataFrame name marks subjects 0 Sush 90 Math 1 John 80 Physics 2 Rick 98 Chemistry 3 Kush 99 English 4 Ipshita 92 Computer After reordering using row index name marks subjects 4 Ipshita 92 Computer 2 Rick 98 Chemistry 1 John 80 Physics 3 Kush 99 English 2 Rick 98 Chemistry
Leave a Reply