sort_values

Use this function to order the rows in your dataframe. Useful if you want to quickly see the top results. Going to use the titanic dataset to illustrate. Here's the raw data.


import pandas as pd
import seaborn as sns

df = sns.load_dataset('titanic')
df.head(5)
          
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
3 1 1 female 35.0 1 0 53.1000 S First woman False C Southampton yes False
4 0 3 male 35.0 0 0 8.0500 S Third man True NaN Southampton no True

Sorting dataframe values

Use the sort_values to order your dataframe. The ascending parameter can be used to reverse the order of results. This chain the 5 oldest people in the dataset.


(
    df
    .sort_values('age', ascending=False)
).head(5)
          
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
630 1 1 male 80.0 0 0 30.0000 S First man True A Southampton yes True
851 0 3 male 74.0 0 0 7.7750 S Third man True NaN Southampton no True
493 0 1 male 71.0 0 0 49.5042 C First man True NaN Cherbourg no True
96 0 1 male 71.0 0 0 34.6542 C First man True A Cherbourg no True
116 0 3 male 70.5 0 0 7.7500 Q Third man True NaN Queenstown no True

Custom sort pandas dataframes

The default order isn't always what you want to sort your dataframe by, you might want to specify an order. A fairly straightforward way to do this is to use pd.Categorical. These are a bit like factors in R, and give you a way to represent a categorical variable in your dataset. Here we'll order the embarkation points by a custom order, rather than the default alphabetical. Combining this with the assign verb as well.


df
.assign(embark_categorical = pd.Categorical(
    df.embark_town,
    ['Southampton', 'Cherbourg', 'Queenstown']
))
.sort_values('embark_categorical')
          
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone embark_categorical
829 1 1 female 62.0 0 0 80.000 NaN First woman False B NaN yes True NaN
61 1 1 female 38.0 0 0 80.000 NaN First woman False B NaN yes True NaN
0 0 3 male 22.0 1 0 7.250 S Third man True NaN Southampton no False Southampton
541 0 3 female 9.0 4 2 31.275 S Third child False NaN Southampton no False Southampton
542 0 3 female 11.0 4 2 31.275 S Third child False NaN Southampton no False Southampton