IndexingΒΆ

The DataFrame index determines how rows are labeled, accessed, and aligned during operations like merging and concatenation. Pandas supports both single-level and multi-level (hierarchical) indices, giving you powerful ways to organize and query your data.

This notebook demonstrates reading data with a custom index column (index_col), switching between custom and default indices with set_index() and reset_index(), label-based row access with .loc[], position-based access with .iloc[], creating a hierarchical MultiIndex from two columns (Continent and Country), sorting multi-indexed DataFrames with .sort_index(), and accessing nested index levels with tuple notation in .loc[].

import pandas as pd
df = pd.read_csv(r"C:\Users\alexf\OneDrive\Documents\Pandas Tutorial\world_population.csv")

df
df = pd.read_csv(r"C:\Users\alexf\OneDrive\Documents\Pandas Tutorial\world_population.csv", index_col = "Country")

df
df.reset_index(inplace=True)
df
df.set_index('Country', inplace = True)

df
df.loc['Albania']
df.iloc[1]
df.reset_index(inplace = True)
df.set_index(['Continent','Country'], inplace=True)
df.sort_index()

#pd.set_option('display.max.rows', 235)
df.loc['Africa','Angola']
df.iloc[1]