Sub topic 2
Selecting one or more columns
This chapter assumes you can write basic Python (lists, dictionaries, strings), have pandas installed and imported as pd, and can build a DataFrame from a dictionary. The index and column labels from the previous chapter are used here without re-explaining them.
The setup
The examples use this DataFrame. The row labels a to e are a string index.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)One name gives a Series, a list gives a DataFrame
Square brackets on a DataFrame select columns. The type of the object inside the brackets decides what you get back.
cities = df["city"] # a Series
subset = df[["city", "population_k"]] # a DataFrame
print(type(cities))
print(type(subset))
print(cities.shape) # (5,)
print(subset.shape) # (5, 2)A single string returns a Series, which is one column with the original index attached. A list of strings returns a DataFrame. The outer brackets are the selection operator, and the inner brackets build an ordinary Python list.
Order and repetition
The list controls the order of the result. You can reorder columns by listing them differently, and you can repeat a name.
reordered = df[["continent", "city"]]
print(reordered.columns.tolist()) # ['continent', 'city']The original df is unchanged. Selection builds a new object each time.
Common errors
The most frequent mistake is passing several names without the inner list.
# Wrong: pandas treats ("city", "population_k") as one tuple key
# df["city", "population_k"] # raises KeyErrorPandas looks for a single column whose label is the tuple ("city", "population_k"). No such column exists, so you get a KeyError. Add the inner brackets to fix it.
A misspelled or differently capitalised name also raises KeyError. Print df.columns to see the exact labels, including stray spaces such as "city ".
Attribute access and its limits
You can also write df.city. It works only when the column name is a valid Python identifier and does not collide with an existing DataFrame attribute. A column named count or size would return the method instead of your data. A name like "population k" cannot be written this way at all. It is also unreliable for assignment: df.new_col = ... sets a plain attribute and does not create a column. Prefer df["city"] in code you plan to keep.
A note on slices
Brackets behave differently when you pass a slice. df["a":"c"] selects rows, not columns. This is a historical shortcut. It is easy to misread, so use .loc or .iloc for rows, as the next chapters show.
Check your understanding
Exercise
Using the DataFrame above, write one line that returns a DataFrame with only the columns country and city, in that order. Then write one line that returns the population_k column as a DataFrame with a single column, not a Series. What shape does each have?
Show answer
df[["country", "city"]] has shape (5, 2). df[["population_k"]] has shape (5, 1). The inner list is what keeps the result a DataFrame, and the list order sets the column order.
Exercise
A teammate writes df["city", "country"] and gets a KeyError. Explain why, and give the fix.
Show answer
Pandas receives the tuple ("city", "country") and looks for a single column with that tuple as its label. There is none. Wrap the names in a list: df[["city", "country"]].