← Back to Pandas Course | Chapter 3: DataFrame Basics | Lesson 4 of 7

Selecting columns

Square brackets pick one column (a Series) or several columns (a smaller DataFrame).

In this page:

  1. Selecting columns
Syntax
python
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

python
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
  1. Forgetting the double brackets for multiple columns
  2. Using dot access on names with spaces
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.