← Data analysis with Python

Choosing columns

One column gives a Series; a list of columns gives a smaller table.

Start this lesson

Most questions only need a few columns. df["high"] (single brackets, one name) gives a Series. df[["month", "high"]] (a list of names inside the brackets) gives a new, narrower DataFrame. The double brackets are not special syntax: the outer brackets select, and the inner brackets are an ordinary Python list of names. For category columns, .unique() lists the different values and .nunique() counts them.

import io
import pandas as pd

csv_text = """day,store,item,units,price
Mon,North,Coffee,30,3.5
Mon,North,Muffin,12,2.75
Mon,South,Coffee,22,3.5
Mon,South,Tea,9,3.0
Tue,North,Coffee,35,3.5
Tue,North,Tea,7,3.0
Tue,South,Coffee,18,3.5
Tue,South,Muffin,15,2.75
Wed,North,Muffin,10,2.75
Wed,South,Coffee,27,3.5
"""
sales = pd.read_csv(io.StringIO(csv_text))
print(sales["item"].unique())
print(sales["item"].nunique())
small = sales[["store", "units"]]
print(small.head())

unique() shows Coffee, Muffin and Tea; nunique() says 3. small is a DataFrame with just two columns.

A KeyError usually means a column name is misspelled or has a different capital letter. Print df.columns to check.