Indexing and multi-indexing

index_col can be used to specify one column to provide row indices. A list of columns can be passed as indices, which leads to multi-indexing. Let's look at an example:

pd.read_csv('mindex.txt')pd.read_csv('mindex.txt',index_col=[0,1])

Take a look at the following screenshot:

Single index (left) and multi-index (right) on the same data

This kind of multi-indexing makes it easy to subset based on either an index or both:

data.loc[1977]data.loc[(1977,'A')]

We get the following output:

Subsetting multi-indexed data ...

Get Mastering pandas - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.