Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

6.2 DataFrames

How it works

A DataFrame is a table with labelled rows and columns. Selecting by label and selecting by position are different operations with different methods.

Select columns by name and rows by condition, keeping the two selection styles distinct.

Common error

Chained selection that returns a copy rather than a view, so an assignment appears to do nothing.

Worked example

These examples require NumPy or pandas, as shown by the imports.

Python

import pandas as pd
df = pd.DataFrame({"name": ["Ada", "Lin"], "score": [7, 9]})
print(df["score"].sum())
print(df.loc[df["score"] >= 8, "name"].tolist())

Output

16
['Lin']

A DataFrame combines named columns with row labels. Use a Boolean condition and an explicit column selection to identify the records needed for an analysis.

Exercises

6.2.1 · Trace

Determine the exact output and explain the state changes.

Python

import pandas as pd
df = pd.DataFrame({"x": [2, 5]})
df["double"] = 2 * df["x"]
print(df["double"].tolist())
Show solution

Output

[4, 10]

The new column is calculated from each corresponding x value.

6.2.2 · Write code

Create a DataFrame with scores [4, 8, 6] and print scores at least 6.

Show solution

Filter with a Boolean mask.

One valid solution

import pandas as pd
df = pd.DataFrame({"score": [4, 8, 6]})
print(df.loc[df["score"] >= 6, "score"].tolist())

Expected output

[8, 6]
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic