How to Sort Pandas DataFrame Based on Values in Python
We can sort data of Pandas DataFrame in Python. In this article, I’ll show here how to sort Pandas DataFrame based on values in Python. Pandas sort_values()
method sorts a data frame in Ascending or Descending order of passed Column.
Syntax: DataFrame.sort_values(by, axis, ascending, inplace, kind, na_position)
Parameters: This method will take following parameters :
by: Single/List of column names to sort Data Frame by.
axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column.
ascending: Boolean value which sorts Data frame in ascending order if True.
inplace: Boolean value. Makes the changes in passed data frame itself if True.
kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of the algorithm used to sort data frame.
na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’.
Return Type: Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame.
I have an another article How to Create a Pandas DataFrame in Python, where you will learn how to create a DataFrame. For this tutorial, create a sample DataFrame as below:
id name math_score 0 202301 Minhaj 92 1 202302 Ridhwan 86 2 202303 Tanveer 76 3 202304 Sharodia 89 4 202305 Alve 99 5 202306 Intisar 99
df.sort_values(by = 'math_score', inplace = True, axis = 0, ascending = False)
print(df)
Output:
id name math_score 4 202305 Alve 99 5 202306 Intisar 99 0 202301 Minhaj 92 3 202304 Sharodia 89 1 202302 Ridhwan 86 2 202303 Tanveer 76
In this tutorial, I tried to brief how to sort sort Pandas DataFrame based on values in Python. Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.