Sub topic 2
Selecting One or More Columns
This chapter covers selecting columns with square brackets. It assumes you can build a DataFrame from a dictionary and have pandas imported as pd. It also assumes you know that a DataFrame has an index, columns, and values. If the difference between an index label and a column name is unclear, review that first.
The data used in this chapter
The examples reuse one small DataFrame with 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"],
)
print(df.index)
print(df.columns)
print(df.dtypes)df.columns is an Index object holding the column names. Bracket selection looks names up in that object. It never looks at positions.
One name or a list of names
The same square brackets do two different things, depending on what you put inside them.
cities = df["city"] # a Series
subset = df[["city", "population_k"]] # a DataFrame
print(type(cities))
print(type(subset))A single name returns a Series, which is a one-dimensional column with the DataFrame's index attached. A list of names returns a DataFrame. The outer brackets are the selection operator. The inner brackets build an ordinary Python list.
The result type follows from the argument type, not from how many columns you ask for. A list with one name still returns a DataFrame.
as_series = df["city"]
as_frame = df[["city"]]
print(as_series.shape) # (5,)
print(as_frame.shape) # (5, 1)This matters when later code expects a particular shape. Methods such as .str, .map, and .value_counts work on a Series. Operations that expect rows and columns, such as .merge and .to_dict("records"), work on a DataFrame.
| You write | You get | Shape for the example |
|---|---|---|
| `df["city"]` | Series | (5,) |
| `df[["city"]]` | DataFrame | (5, 1) |
| `df[["city", "country"]]` | DataFrame | (5, 2) |
| `df[[]]` | DataFrame with no columns | (5, 0) |
Order, repeats, and building lists
A list selection returns columns in the order you list them, not the order they have in the original DataFrame. That makes it a simple way to reorder columns.
reordered = df[["population_k", "city", "country"]]
print(reordered.columns.tolist())You can also repeat a name. The result then has two columns with the same label, which usually causes trouble later. Selecting that label returns a DataFrame instead of a Series.
doubled = df[["city", "city"]]
print(doubled.shape) # (5, 2)
print(type(doubled["city"])) # a DataFrame, not a SeriesThe list can come from anywhere, so you can store it in a variable and reuse it.
wanted = ["city", "population_k"]
print(df[wanted].head(2))To keep everything except a few columns, use drop instead of typing the long list that remains.
print(df.drop(columns=["country"]).columns.tolist())drop returns a new DataFrame and leaves df unchanged.
When the name is wrong
A name that is not in the columns raises a KeyError. The message differs slightly between the two forms.
try:
df["density"]
except KeyError as err:
print("single:", err)
try:
df[["city", "density"]]
except KeyError as err:
print("list:", err)The single-name message shows the missing key. The list message names only the labels that are missing, which helps when the list is long. The usual causes are:
- A typo or a different capitalization. Column names are case-sensitive, so
"City"and"city"are different columns. - Stray whitespace in a name, often from a CSV header. A column called
"city "does not match"city". - A column that exists only in a different DataFrame, for example before a merge.
When you suspect whitespace, print df.columns.tolist(). A list shows quotes around each name, so trailing spaces are visible. The default Index display makes them harder to spot.
If you want to select whichever of a set of columns happen to exist, filter the list first.
candidates = ["city", "density", "population_k"]
present = [c for c in candidates if c in df.columns]
print(df[present].columns.tolist())Attribute access and its limits
Pandas also lets you write df.city. This works because pandas exposes valid column names as attributes. It is convenient in interactive work, but it has three limits.
- The name must be a valid Python identifier. A column called
"pop k"or"2024"cannot be written as an attribute. - A column whose name matches an existing DataFrame attribute is shadowed by that attribute.
- It cannot create a column.
The second limit is the most common source of silent mistakes.
counts = pd.DataFrame({"count": [4, 5], "index": [10, 20]})
print(type(counts.count)) # a bound method, not the column
print(type(counts["count"])) # a Series
print(counts.index) # the real index, not the "index" column
print(counts["index"].tolist())For the third limit, writing df.density = ... sets a plain Python attribute on the object and does not add a column. Pandas typically emits a UserWarning about it. Use df["density"] = ... to create or replace a column.
Brackets with non-string labels
Column labels do not have to be strings. If the columns are integers, df[0] looks up the column labeled 0. It does not take the first column by position.
numbered = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=[10, 20, 30])
print(numbered[20].tolist()) # column labeled 20
print(numbered[[10, 30]].shape)This is the same rule as before: brackets match labels. Selecting the first column by position is a job for .iloc, which a later chapter covers.
A quirk: slices select rows
One use of brackets does not select columns at all. A slice inside the brackets selects rows.
print(df[0:2]) # first two rows, by position
print(df["a":"c"]) # rows a through c, by label, end includedThis is a shortcut that exists for historical reasons, and its behavior differs from the column cases above. The first form excludes the end position, and the second includes the end label. Because the rules are easy to forget, most code reserves brackets for columns and uses .loc and .iloc for rows. Those two selectors are covered in the next chapters.
Does the result share memory with the original?
A common worry is whether changing the selected columns changes df. The answer depends on your pandas version, and for that reason you should not rely on either behavior.
- In pandas 3 and in pandas 2 with Copy-on-Write enabled, the selection behaves as an independent object. Changing it does not change
df. - In older default behavior, some selections could be views of the original data, and the library gave no guarantee either way.
If you plan to modify a selection, make the intent explicit.
work = df[["city", "population_k"]].copy()
work["population_k"] = work["population_k"] * 1000
print(df["population_k"].tolist()) # unchangedCalling .copy() costs a memory copy, but it removes any dependence on version-specific behavior. The final chapters of this tutorial cover assignment and SettingWithCopyWarning in detail.
Common mistakes
- Writing
df["city", "country"]. This passes a tuple, which pandas treats as one label, and it raises aKeyError. Usedf[["city", "country"]]. (A tuple is meaningful only when the columns have a multi-level index.) - Expecting
df[["city"]]to behave like a Series. It is a DataFrame, so.stris not available on it directly. - Using attribute access for names with spaces, or for names such as
count. - Expecting
df[2]to return the third column when the columns are strings. It raises aKeyError.
Exercise
Given the DataFrame df from this chapter, write one expression that returns a DataFrame with the columns continent and city, in that order. Then write an expression that returns the continent column as a Series. Finally, say what df[["continent"]].shape returns and why it differs from df["continent"].shape.
Show answer
Use df[["continent", "city"]] for the first and df["continent"] for the second. df[["continent"]].shape is (5, 1) because a list argument always returns a DataFrame, even with one name. df["continent"].shape is (5,) because a single name returns a one-dimensional Series.
Exercise
A DataFrame has a column named size. What does data.size return, and how do you get the column itself?
Show answer
data.size returns the DataFrame's built-in size attribute, which is the total number of elements (rows times columns), not the column. Use data["size"] to get the column as a Series.