Order Rows of pandas DataFrame by Column in Python (Example Code)
This article demonstrates how to order a pandas DataFrame by the values in a column in the Python programming language.
Preparing the Example
import pandas as pd # Load pandas library |
import pandas as pd # Load pandas library
my_df = pd.DataFrame({'A':[10, 33, 5, 1, 18], # Construct example DataFrame 'B':['a', 'b', 'c', 'd', 'e']}) print(my_df) # Display example DataFrame in console # A B # 0 10 a # 1 33 b # 2 5 c # 3 1 d # 4 18 e |
my_df = pd.DataFrame({'A':[10, 33, 5, 1, 18], # Construct example DataFrame 'B':['a', 'b', 'c', 'd', 'e']}) print(my_df) # Display example DataFrame in console # A B # 0 10 a # 1 33 b # 2 5 c # 3 1 d # 4 18 e
Example: Sorting Rows of pandas DataFrame Using sort_values() Function
my_df = my_df.sort_values('A') # Sorting data by column print(my_df) # Display DataFrame once again # A B # 3 1 d # 2 5 c # 0 10 a # 4 18 e # 1 33 b |
my_df = my_df.sort_values('A') # Sorting data by column print(my_df) # Display DataFrame once again # A B # 3 1 d # 2 5 c # 0 10 a # 4 18 e # 1 33 b