6.18. DataFrame Sort
.sort_index(ascending, axis).sort_values(by, ascending, axis)Works with
inplace=Trueaxis=0- Rowsaxis=1- Columns
6.18.1. SetUp
>>> import pandas as pd
>>>
>>> df = pd.DataFrame([
... {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
... {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
... {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... ], index=['a', 'b', 'c'])
>>> df
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
6.18.2. Sort by Values
DataFrame.sort_values(by, ascending)
>>> df.sort_values('lastname')
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
>>> df.sort_values('lastname', ascending=True)
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
>>> df.sort_values('lastname', ascending=False)
firstname lastname age
c Carol Corn 32
b Bob Blackthorn 31
a Alice Apricot 30
6.18.3. Sort by Multiple Values
DataFrame.sort_values(by=[...], ascending=[...])
>>> df.sort_values(by=['lastname', 'firstname'], ascending=False)
firstname lastname age
c Carol Corn 32
b Bob Blackthorn 31
a Alice Apricot 30
>>> df.sort_values(by=['lastname', 'firstname'], ascending=[True, False])
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
6.18.4. Sort by Index
DataFrame.sort_index(ascending)
>>> df.sort_index()
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
>>>
>>>
>>> df.sort_index(ascending=True)
firstname lastname age
a Alice Apricot 30
b Bob Blackthorn 31
c Carol Corn 32
>>>
>>>
>>> df.sort_index(ascending=False)
firstname lastname age
c Carol Corn 32
b Bob Blackthorn 31
a Alice Apricot 30