sort_index returns a new pandas DataFrame with the same content as the original, but with rows ordered by index values. With a MultiIndex, pandas sorts primarily by the first level, then by the next levels. section 4.10 section 4.8
Sort an Olympic MultiIndex
Create a DataFrame indexed by Year, Season, Sport, and Event, then sort it with df = df.sort_index(). The resulting rows are ordered by Year, then Season, Sport, and Event, making later index-based questions easier to perform. section 4.10
Sorting the index is useful when:
- Selecting ordered slices such as df.loc['a':'c'], which requires a sorted index to avoid interspersed boundary values. section 4.8
- Working with a large or multi-indexed DataFrame, where an unsorted index can produce a PerformanceWarning. section 4.10 section 4.8
filename = '../data/olympic_athlete_events.csv'
df = pd.read_csv(filename,
index_col=['Year', 'Season',
'Sport', 'Event'], #1
usecols=['Age', 'Height', 'Team',
'Year', 'Season', 'City',
'Sport', 'Event', 'Medal']) #2
df = df.sort_index() #3
Follow the complete pattern from CSV loading with four index columns through assigning the sorted DataFrame. section 4.10
