Indexing

Understand how DataFrame values can be accessed via indexing.

Chapter Goals:

  • Learn how to index a DataFrame to retrieve rows and columns
  • Write code for indexing a DataFrame

A. Direct indexing

When indexing into a DataFrame, we can treat the DataFrame as a dictionary of Series objects, where each column represents a Series. Each column label then becomes a key, allowing us to directly retrieve columns using dictionary-like bracket notation.

The code below shows how to directly index into a DataFrame's columns.

Press + to interact
df = pd.DataFrame({'c1': [1, 2], 'c2': [3, 4],
'c3': [5, 6]}, index=['r1', 'r2'])
col1 = df['c1']
# Newline for separating print statements
print('{}\n'.format(col1))
col1_df = df[['c1']]
print('{}\n'.format(col1_df))
col23 = df[['c2', 'c3']]
print('{}\n'.format(col23))

Note that when we use a single column label inside the bracket (as was the case for col1 in the code example), the output is a Series representing the corresponding column. When we use a list of column labels (as was the ...