Real datasets often have dozens or hundreds of columns, and you rarely need them all. Selecting columns is how you focus on the ones that matter: the price and area of a house, the features for a model, or the three columns your manager asked for in a report.
This lesson covers every common way to select columns in pandas: by name, by position, by data type and by a pattern in the name, plus how to drop and reorder them.
We'll use this small table of mobile phones throughout:
import pandas as pd
phones = pd.DataFrame({
"brand": ["Samsung", "Apple", "Xiaomi", "OnePlus", "Realme"],
"model": ["M34", "iPhone 15", "Redmi 13", "Nord 4", "Narzo 70"],
"price": [15999, 79900, 11499, 29999, 13499],
"ram_gb": [6, 6, 8, 8, 6],
"storage_gb": [128, 128, 128, 256, 128],
"rating": [4.2, 4.6, 4.1, 4.4, 4.0],
})
Select one column
Put the column name in square brackets. The result is a Series:
print(phones["price"])
0 15999
1 79900
2 11499
3 29999
4 13499
Name: price, dtype: int64
You'll also see dot notation, phones.price. It's shorter, but it only works when the name is a valid Python identifier (no spaces, doesn't start with a number) and doesn't clash with a DataFrame method. A column called count or size can't be read this way, because phones.count is a method. Square brackets always work, so prefer them.
Select several columns
Pass a list of names, which means two sets of square brackets: the outer ones select, the inner ones make the list. The result is a DataFrame, in the order you list:
print(phones[["model", "price"]])
model price
0 M34 15999
1 iPhone 15 79900
2 Redmi 13 11499
3 Nord 4 29999
4 Narzo 70 13499
Keeping the list in a variable makes code easier to read, and it's how you'd usually pick features for a model:
features = ["price", "ram_gb", "storage_gb"]
X = phones[features]
To get one column as a DataFrame rather than a Series, use a one-item list: phones[["price"]].
Select columns by position
Use iloc with : for "all rows" and positions for columns:
print(phones.iloc[:, 0]) # first column as a Series
print(phones.iloc[:, -2:]) # last two columns
print(phones.iloc[:, [0, 2]]) # columns 0 and 2
Positions are fragile: if someone adds a column to the source file, position 2 might suddenly be a different column. Use names when you can. loc vs iloc in pandas covers both in depth.
Select columns by data type
select_dtypes picks columns by type, which is very handy before calculating statistics or scaling features:
print(phones.select_dtypes(include="number").columns.tolist())
# ['price', 'ram_gb', 'storage_gb', 'rating']
print(phones.select_dtypes(exclude="number").columns.tolist())
# ['brand', 'model']
Useful values for include: "number", "object" (text), "bool", "datetime" and "category".
Select columns by name pattern
filter selects columns whose names match a pattern. like matches any part of the name; regex takes a regular expression:
print(phones.filter(like="_gb").columns.tolist())
# ['ram_gb', 'storage_gb']
print(phones.filter(regex="^(brand|model)$").columns.tolist())
# ['brand', 'model']
A list comprehension over phones.columns does the same with plain Python, and works for any rule you can write:
cols = [c for c in phones.columns if c.endswith("_gb")]
See the column names first
Before selecting, you need the exact names:
print(phones.columns.tolist())
['brand', 'model', 'price', 'ram_gb', 'storage_gb', 'rating']
Real files often have messy names like " Price (₹) ", with spaces you can't see. A KeyError on a name that looks right usually means hidden spaces. Clean all names at once:
phones.columns = phones.columns.str.strip().str.lower().str.replace(" ", "_")
Drop columns you don't need
Sometimes it's easier to say what you don't want:
print(phones.drop(columns=["model", "rating"]).columns.tolist())
# ['brand', 'price', 'ram_gb', 'storage_gb']
drop returns a new DataFrame. To change phones itself, assign the result back: phones = phones.drop(columns=[...]).
Reorder columns
Select them in the order you want:
phones = phones[["model", "brand", "price", "rating", "ram_gb", "storage_gb"]]
To move just one column to the front without typing every name:
cols = ["price"] + [c for c in phones.columns if c != "price"]
phones = phones[cols]
print(phones.columns.tolist())
['price', 'model', 'brand', 'rating', 'ram_gb', 'storage_gb']
Common errors
| Error | Cause | Fix |
|---|---|---|
KeyError: 'Price' | Names are case-sensitive, or have hidden spaces | Print df.columns.tolist() and copy the exact name |
KeyError: ('model', 'price') | Wrote phones["model", "price"] with single brackets | Use a list: phones[["model", "price"]] |
AttributeError with df.my col | Dot notation doesn't work with spaces | Use df["my col"] |
Practice
- Select
brand,priceandratingfromphones.
Show the answer
print(phones[["brand", "price", "rating"]])
- Calculate the mean of every numeric column in one line.
Show the answer
print(phones.select_dtypes(include="number").mean())
- Select every column except
model, in two different ways.
Show the answer
a = phones.drop(columns=["model"])
b = phones[[c for c in phones.columns if c != "model"]]
Interview questions
What is the difference between df["a"] and df[["a"]]?
df["a"] returns a Series (one column, one dimension). df[["a"]] passes a list and returns a DataFrame with a single column (two dimensions). Many scikit-learn functions want the DataFrame form for features.
Why prefer df["col"] to df.col?
Bracket access works for any column name, including names with spaces, names starting with numbers, and names that clash with DataFrame attributes like count or size. It's also the only way to create a new column.
How do you select all numeric columns in pandas?
df.select_dtypes(include="number"). Pass exclude="number" for everything else.
What to learn next
- Select rows and columns together in loc vs iloc in pandas.
- Keep only the rows you need in filter rows in pandas.