Select CSV columns with pandas

How to select CSV columns in pandas with usecols, bracket indexing, loc, iloc and filter, and how to keep values, order and formatting intact.

Selecting columns from a CSV file with pandas is a projection: you keep some fields and drop the rest. The values in the columns you keep are not supposed to change. In practice, the round trip through pandas can alter how those values look. Leading zeros, empty cells, number formatting and column order can all shift unless you control them. This review explains the main selection methods, what each one changes, and when a simpler plain-text tool is the better choice.

Is pandas the right tool for selecting columns?

Pandas is a good fit when the selected columns feed further analysis in Python, or when you need to choose columns by name, pattern or condition. Its main advantage is that it parses CSV properly, including quoted fields that contain commas or line breaks. Its main tradeoff is type inference: by default it converts text to numbers, dates and missing values, then writes them back in its own format. Most of the time that is harmless. It matters when the output must match the source text exactly.

Plain-text handling is preferable when you need a byte-faithful extract for an audit, a diff or a system that expects the original formatting. In that case, read everything as strings with missing-value conversion turned off, or use a dedicated CSV command-line tool. A basic delimiter splitter such as cut is only safe when no field contains the delimiter inside quotes, because it does not understand CSV quoting.

Selecting columns while reading: usecols

The read_csv function accepts a usecols argument. It can be a list of column names, a list of integer positions, or a function that receives each header name and returns True for columns to keep. The parser then discards the other columns instead of building them into the DataFrame. This can reduce memory use for wide files, but the file is still read from start to finish. No measurements were available for this review, so the size of the saving on any particular file is not stated here.

import pandas as pd

# By name
df = pd.read_csv("orders.csv", usecols=["order_id", "customer", "total"])

# By position (0-based)
df = pd.read_csv("orders.csv", usecols=[0, 2, 5])

# By rule: keep every column whose header starts with "sales_"
df = pd.read_csv("orders.csv", usecols=lambda name: name.startswith("sales_"))

The pandas documentation notes that usecols ignores the order of its elements. The resulting columns follow the order of the file, not the order of your list. To get a specific order, index the result again after reading.

cols = ["total", "order_id", "customer"]
df = pd.read_csv("orders.csv", usecols=cols)[cols]

If a name in usecols does not exist in the header, read_csv raises a ValueError rather than silently returning fewer columns. This often happens because of stray spaces or capitalization differences in the header row. Using a function for usecols, for example one that strips and lowercases each name before comparing, is more tolerant of messy headers.

Selecting columns after reading

Once the data is in a DataFrame, several selection methods are available. They differ in how you identify columns and in what they return.

Method | Selects by | Returns | Notes
df["a"] | Single label | Series | Not a DataFrame; behaves differently when written or joined
df[["a", "b"]] | List of labels | DataFrame | Keeps the order you list; missing label raises KeyError
df.loc[:, "a":"c"] | Label range | DataFrame | Range includes both ends and follows current column order
df.iloc[:, [0, 2]] | Integer positions | DataFrame | Depends on column order, which can change between file versions
df.filter(like="date") | Substring in label | DataFrame | Missing matches give an empty result, not an error
df.filter(regex="^q[1-4]_") | Regular expression | DataFrame | Same silent-empty behavior as like
df.drop(columns=["x"]) | Labels to remove | DataFrame | Useful when keeping most columns
subset = df[["order_id", "total"]]
by_range = df.loc[:, "order_date":"ship_date"]
by_pos = df.iloc[:, [0, 3]]
quarterly = df.filter(regex=r"^q[1-4]_")
trimmed = df.drop(columns=["internal_notes"])

A common mistake is using single brackets when a one-column DataFrame is needed. df["total"] gives a Series, while df[["total"]] gives a DataFrame with one column. The difference matters for functions that expect a table, and for to_csv, which writes a Series with slightly different header handling.

Name-based selection is generally safer than position-based selection for files that are produced by other people or systems. If a column is inserted upstream, positional selection quietly returns the wrong data, while name-based selection either still works or fails with an error you can see. Pattern-based selection with filter sits in between: it adapts to new matching columns but returns an empty table instead of raising an error when nothing matches, so check the result.

If you plan to modify the subset, call .copy() on it. This makes clear that changes apply to the subset rather than the original DataFrame and avoids warnings about chained assignment that some pandas versions raise.

What selection changes, and what it should not

Selecting columns removes fields and may reorder them. It does not change the content of kept columns by itself. The changes people notice usually come from reading and writing, not from the selection step. These are the ones that most often alter meaning:

  • Leading zeros: identifiers such as ZIP codes, account numbers or product codes are read as integers by default, so 01234 becomes 1234.
  • Missing-value markers: strings such as NA, N/A, null and empty cells are converted to NaN by default and written back as empty fields.
  • Number formatting: floats are written in pandas' own representation, which may differ from the original text in trailing zeros or precision.
  • Dates: text is only parsed as dates if you ask for it, but once parsed, dates are written in a standard format rather than the source format.
  • Duplicate headers: if two columns share a name, read_csv renames the second one, for example to total.1, which changes the header in any file you write back.
  • Header whitespace: a header written as " customer" is a different label from "customer" and will not match unless you strip it.

To keep the selected values exactly as they appear in the source, read them as text and disable default missing-value detection. This sacrifices numeric operations until you convert columns deliberately.

df = pd.read_csv(
    "orders.csv",
    usecols=["zip", "account", "total"],
    dtype=str,
    keep_default_na=False,
)
df.columns = df.columns.str.strip()

A middle path is to set dtype only for the identifier columns, for example dtype={"zip": str, "account": str}, and let pandas infer the rest.

Will the output stay usable after you save or share it?

Most problems with shared output come from to_csv defaults. By default it writes the DataFrame index as an extra first column with no header. Recipients then see an unexplained column of numbers. Pass index=False unless the index carries real data.

df.to_csv("orders_subset.csv", index=False)

Delimiter and encoding also affect usability. If the source used semicolons or tabs, read it with sep=";" or sep="\t" and decide whether the output should keep that delimiter. Pandas writes UTF-8 by default. Some spreadsheet applications detect UTF-8 more reliably when the file begins with a byte order mark, which you can add with encoding="utf-8-sig". Behavior varies by application and version, and no destination was tested for this review, so open the file in the program your recipients actually use before relying on it.

Pandas quotes fields that contain the delimiter, quote characters or line breaks, so the output stays valid CSV for CSV-aware readers. Line-oriented tools that split on every comma or newline can still misread those fields. If the output is headed for such a tool, or for a person who will read it as plain text, check whether any kept column contains embedded commas or line breaks and consider removing or replacing them first.

Practical recommendation

Use usecols with column names when you know which fields you need before loading, especially with wide files. Reindex the result if column order matters. Use bracket selection with a list of names for most work after loading, and reserve position-based and pattern-based selection for files whose layout you control or check. Set string types for identifiers, and write with index=False. When the extract must match the source text exactly, read everything as strings with missing-value detection off, or use a CSV-aware command-line tool instead of pandas.

Gaps in this review

This review is based on documented pandas behavior and general CSV conventions. It does not include performance or memory measurements, version-by-version testing, or checks of how specific spreadsheet programs or other destinations display the output. Defaults and warnings can differ between pandas releases, so confirm behavior against the documentation for the version you have installed.