How to convert pandas dataframe to tensorflow dataset?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Converting a pandas DataFrame to a TensorFlow dataset is a common step when moving from exploratory data work into model training. The easiest path is usually tf.data.Dataset.from_tensor_slices, but the correct structure depends on whether you have labels, mixed feature types, or data too large to materialize comfortably in memory. The goal is not just conversion, but building a dataset that trains cleanly and predictably.
Convert Features and Labels Explicitly
For supervised learning, split the DataFrame into features and labels before conversion. TensorFlow works best when the dataset element shape matches the model input structure.
Using dict(features) is convenient because each column becomes a named tensor, which maps naturally to Keras feature inputs.
Batch, Shuffle, and Prefetch
A raw dataset works, but most training pipelines also need batching and shuffling.
This is where tf.data starts adding real value over passing arrays directly to model.fit.
Handle Numeric Arrays for Simpler Models
If your model expects a single dense tensor rather than named inputs, convert the feature frame to a NumPy array.
This is often the simplest path for dense tabular models.
Be Careful with String and Categorical Columns
Mixed dtypes can surprise you. String columns are supported, but many models need them encoded before training. You can either preprocess in pandas first or use Keras preprocessing layers.
The conversion works, but the model still needs a strategy for turning "city" into useful numeric features.
Use a Generator Only When Necessary
from_tensor_slices is usually best for in-memory data. Use from_generator only when you truly need streaming behavior or custom row-by-row logic.
This is more flexible, but also more verbose and slower if you use it without a real need.
Match Dataset Structure to Model Inputs
The most common source of errors is a mismatch between dataset elements and model input signatures. If the model expects named inputs, yield a dictionary. If it expects one tensor, yield one tensor. Keep that alignment explicit rather than relying on automatic coercion.
It is also worth validating one batch before training starts. A quick for loop over dataset.take(1) often reveals dtype or shape mistakes much faster than waiting for a model error inside fit.
Common Pitfalls
- Passing the whole DataFrame directly without separating labels first.
- Mixing object dtype columns into numeric pipelines without conversion.
- Using
from_generatorwhenfrom_tensor_sliceswould be simpler and faster. - Forgetting to batch and prefetch before training.
- Producing dataset elements whose structure does not match the model input signature.
Summary
- Split DataFrame features and labels before conversion.
- Use
from_tensor_slicesfor the normal in-memory case. - Choose dictionary inputs or dense arrays based on model structure.
- Clean up string and categorical columns deliberately before training.
- Add batching, shuffling, and prefetching so the dataset is training-ready.
Related reading
- How to convert .pb to TFLite format?
- How to Convert Ragged Tensor to Tensor in Python?
- how to convert saved model from sklearn into tensorflow/lite
- how to convert saved model from sklearn into tensorflow/lite
- How to convert Tensorflow dataset to 2D numpy array
- How to convert tf.int64 to tf.float32?
- How to convert SQL Query result to PANDAS Data Structure?
- How to count number of records (message) in the topic using kafka-python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.