2.6 Sorting
Like native Python lists and dictionaries, DataFrames can also An action that changes the order of records in a dataset based on rules. by one or more columns. We do this using either the Pandas DataFrame method used to sort objects by labels along either rows or columns. or the Pandas DataFrame method used to sort objects by values along either rows or columns. method.
As you might have guessed, sort_index() will sort whatever the row index is set to by default. Remember that if a labeled index is not set, then a numeric RangeIndex is autogenerated and used. However, if you set a labeled row index, and if that index is not sorted alphabetically, then sort_index() will take care of that. You can also reverse sort:
import pandas as pd
df = pd.DataFrame({'age':[29, 55, 65, 18], 'gender':['male', 'female', 'male', 'female'], 'hr1':[98.1, 78, 65, 64], 'hr2':[110, 120, 129, 141], 'hr3':[76, 87, 77, 59]}, index=['p1', 'p2', 'p3', 'p4'])
df.sort_index(ascending=False, inplace=True)
df
You can use this method for column indexes as well:
import pandas as pd
df = pd.DataFrame({'age':[29, 55, 65, 18], 'gender':['male', 'female', 'male', 'female'], 'hr1':[98.1, 78, 65, 64], 'hr2':[110, 120, 129, 141], 'hr3':[76, 87, 77, 59]}, index=['p1', 'p2', 'p3', 'p4'])
df.sort_index(ascending=False, inplace=True, axis=1)
df
You can sort by the values in a row or column as well using sort_values:
import pandas as pd
df = pd.DataFrame({'age':[29, 55, 65, 18], 'gender':['male', 'female', 'male', 'female'], 'hr1':[98.1, 78, 65, 64], 'hr2':[110, 120, 129, 141], 'hr3':[76, 87, 77, 59]}, index=['p1', 'p2', 'p3', 'p4'])
df.sort_values(by=['age'], inplace=True)
df
In addition, you can sort by multiple levels:
import pandas as pd
df = pd.DataFrame({'age':[29, 55, 65, 18], 'gender':['male', 'female', 'male', 'female'], 'hr1':[98.1, 78, 65, 64], 'hr2':[110, 120, 129, 141], 'hr3':[76, 87, 77, 59]}, index=['p1', 'p2', 'p3', 'p4'])
df.sort_values(by=['gender', 'age'], inplace=True)
df