Sorting is one of the most common tasks in programming. So, we will also need to performing sorting with Pandas. Pandas provides us with sorting methods that are very useful. In this article, we will see how to sort a pandas DataFrame by its Values.
To story a data frame by values, we use the sort_values
method and pass a column name(s) to the by
name parameter. Let's see an example of how to sort by single and multiple columns.
import pandas as pd
df = pd.DataFrame([
{
"person": "James",
"sales": 1000,
"lastName": "Taylor",
},
{
"person": "Clara",
"sales": 3000,
"lastName": "Brown"
},
{
"person": "Greg",
"sales": 3000,
"lastName": "Genee"
}
])
# Sort by single column
sortedDf = df.sort_values(by='sales')
print(sortedDf.head())
# Sort by multiple columns
sortedDf2 = df.sort_values(by=['sales', 'pearson'])
print(sortedDf2.head())