Selecting columns
Square brackets pick one column (a Series) or several columns (a smaller DataFrame).
In this page:
Syntax
df["column"]
df[["column1", "column2"]]
Selecting columns
df["name"] returns a Series, while df[["name", "age"]] with a list returns a DataFrame. Attribute access df.name works for simple names but not for names with spaces or that clash with methods. Bracket access is the safest form.
Note:
Double brackets return a DataFrame even for one column.
Example: Selecting columns
import pandas as pd
df = pd.DataFrame({"name": ["Ann", "Bob"], "age": [28, 35], "city": ["Oslo", "Rome"]})
print(type(df["age"]).__name__)
print(type(df[["age"]]).__name__)
print(df[["name", "city"]])
# Output:
# Series
# DataFrame
# name city
# 0 Ann Oslo
# 1 Bob Rome
Related Topics
Common Mistakes
- Forgetting the double brackets for multiple columns
- Using dot access on names with spaces
- Misspelling a column and getting KeyError
Chapter Summary
- One label returns a Series
- A list of labels returns a DataFrame
- Bracket access is safest
- Dot access has limits
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: