How to select specific columns from tensorflow dataset?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
TensorFlow input pipelines often start from wide tabular data where only a subset of features is needed for one model. Selecting columns early makes training faster, reduces memory use, and prevents accidental feature drift between training and inference. The tf.data API gives you a clean way to do this with deterministic transformations.
Select Feature Keys from Dictionary Elements
When each dataset element is a dictionary, the most direct pattern is to map every element to a smaller dictionary that keeps only required keys. This keeps schema decisions explicit and visible in code review.
Use a single selected_keys definition that both training and serving code can import. If feature choices are hard coded in several files, drift appears quickly when the schema changes.
Preserve Column Order for Dense Model Inputs
Some models expect a single dense tensor instead of a dictionary. In that case, select columns and stack them in one explicit order. The order must be fixed and documented because changing order changes model meaning.
If your preprocessing team keeps feature definitions in metadata, generate ordered_columns from that source once and version it. That gives you traceability when a model is retrained months later.
Select Columns While Reading CSV Data
For CSV workflows, you can reduce work even earlier by selecting only needed columns during ingestion. This avoids reading unnecessary fields into downstream steps.
This pattern is useful for shared data tables where each team uses different slices of the same source. It also lowers parsing overhead in large pipelines.
Common Pitfalls
- Selecting columns late in the pipeline. Move selection close to ingestion so expensive transforms do not process unused fields.
- Inconsistent feature sets between training and inference. Store selected keys in one shared constant and reuse it in both paths.
- Unstable column ordering when producing dense tensors. Use one ordered list and treat reordering as a breaking change.
- Silent schema breakage after upstream table changes. Add a startup check that validates required keys before training starts.
- Mixing label fields into the feature map. Keep labels separate to avoid accidental leakage and wrong metrics.
Summary
- Use
Dataset.mapto narrow dictionary elements to the exact feature keys you need. - For dense model input, stack selected columns in a fixed documented order.
- For CSV input, prefer
select_columnsat read time to reduce unnecessary parsing. - Centralize feature selection metadata so training and serving remain aligned.
- Add lightweight schema checks to detect drift early.

