Sort a DataFrame by rows and columns in Pandas
Soring a DataFrame in ascending and descending order is very easy in Pandas. We are explaining methods and techniques that can be helpful to sort a DataFrame by rows and columns.
import pandas as pd
data = {
'score_1': [30, 40, 25, 19, 60, 15],
'score_2': [3, 7, 9, 2, 5, 11]
}
# create dataframe
df = pd.DataFrame(data)
# sort DataFrame - ascending order
result = df.sort_values(by='score_1')
print(result)
Output
score_1 score_2
5 15 11
3 19 2
2 25 9
0 30 3
1 40 7
4 60 5
We are using the sort_values() function of DataFrame to sort row values in ascending and descending order. By default, the function sort the values in ascending order. if you want to sort the values in descending order, you can pass asending=False to the sort_values() function.
Sort by multiple columns
To sort a Dataframe by multiple columns values, we can pass the list of column names that you want to sort in the "by" argument of sort_values() function.
import pandas as pd
data = {
'score_1': [30, 40, 25, 19, 60, 15],
'score_2': [3, 7, 9, 2, 5, 11]
}
# create dataframe
df = pd.DataFrame(data)
# sort DataFrame by multiple columns
result = df.sort_values(by=['score_1', 'score_2'])
print(result)
Output
score_1 score_2
5 15 11
3 19 2
2 25 9
0 30 3
1 40 7
4 60 5
Sort DataFrame in Descending order
When we use the sort_values() function of DataFrame to sort the column values, it will sort them in ascending order by default. To sort the values in descending order, set ascending=False. Check the below example for reference
Code Example
import pandas as pd
data = {
'company': ['Devsheet', 'Tesla', 'Microsoft', 'Amazon', 'SpaceX'],
'value': [20, 50, 30, 90, 10]
}
# create dataframe
df = pd.DataFrame(data)
# sort DataFrame in descending order
result = df.sort_values(by='value', ascending=False)
print(result)
Output
company value
3 Amazon 90
1 Tesla 50
2 Microsoft 30
0 Devsheet 20
4 SpaceX 10
- Create pandas DataFrame and add columns and rows to it
- Get the count of rows and columns of a Pandas DataFrame
- Reorder dataframe columns using column names in pandas
- Change the name of columns in a pandas dataframe
- Delete one or multiple columns from Pandas Dataframe
- Select specific columns from a Pandas DataFrame
- Loop through DataFrame rows in python pandas