To turn a pandas DataFrame into a TensorFlow Dataset, pass its columns and the label Series to tf.data.Dataset.from_tensor_slices(). You can then train a model on it in Python.
My first try, tf.convert_to_tensor(df), failed with a ValueError: the file mixes text and numbers, and a tensor holds one dtype. A dict of columns doesn’t have that limit.
Quick answer: pop the label column, slice a dict of the remaining columns, then shuffle and batch:
labels = df.pop("churned")
ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))
ds = ds.shuffle(len(df)).batch(32)
In this tutorial, I’ll walk through each pandas DataFrame to TensorFlow Dataset pattern from that project, the plain DataFrame-to-tensor route, and the errors I hit along the way.
All outputs come from real runs on Python 3.12.5, TensorFlow 2.21.0 and pandas 3.0.6 on Windows.
The Sample Pandas DataFrame We’ll Convert
Every example reads customers.csv: eight US customers with a state, plan, tenure in months, monthly price in USD, support calls and a 0/1 churned label.
state,plan,tenure_months,monthly_usd,support_calls,churned
TX,basic,3,19.99,4,1
CA,pro,14,49.00,1,0
NY,pro,27,49.00,0,0
FL,basic,2,19.99,5,1
WA,team,31,99.00,1,0
TX,pro,9,49.00,2,0
CA,basic,5,19.99,3,1
NY,team,40,99.00,0,0
If TensorFlow isn’t installed yet, start with installing TensorFlow. I load the file with pd.read_csv(), as in reading a CSV file with pandas, and pandas 3 reads state and plan as its new str dtype.
Each script opens with one os.environ.update() line. TF_CPP_MIN_LOG_LEVEL="3" hides TensorFlow’s C++ logs, and TF_ENABLE_ONEDNN_OPTS="0" turns off oneDNN custom ops, which also removes their start-up notice. The conversions work the same without it.
Convert Numeric Columns to a TensorFlow Dataset with from_tensor_slices()
When every feature is a number, pass a NumPy array of features and the label array as a tuple. from_tensor_slices() cuts along the first axis, so each element is one row:
import os
os.environ.update(TF_CPP_MIN_LOG_LEVEL="3", TF_ENABLE_ONEDNN_OPTS="0")
import pandas as pd
import tensorflow as tf
df = pd.read_csv("customers.csv")
labels = df.pop("churned")
features = df[["tenure_months", "monthly_usd", "support_calls"]]
ds = tf.data.Dataset.from_tensor_slices(
(features.to_numpy(dtype="float32"), labels.to_numpy()))
for spec in ds.element_spec:
print(spec)
print("rows:", ds.cardinality().numpy())
for x, y in ds.take(2):
print(x.numpy(), "->", y.numpy())
Output:
TensorSpec(shape=(3,), dtype=tf.float32, name=None)
TensorSpec(shape=(), dtype=tf.int64, name=None)
rows: 8
[ 3. 19.99 4. ] -> 1
[14. 49. 1.] -> 0

I cast to float32 on purpose: pandas defaults to float64, and Keras layers compute in float32, so you’d convert anyway.
You can also convert the columns first, as shown in changing a pandas column data type.
How Do I Keep DataFrame Column Names in a tf.data.Dataset?
Pass dict(df) instead of an array, and you get one named feature per column, each with its own dtype:
import os
os.environ.update(TF_CPP_MIN_LOG_LEVEL="3", TF_ENABLE_ONEDNN_OPTS="0")
import pandas as pd
import tensorflow as tf
df = pd.read_csv("customers.csv")
labels = df.pop("churned")
ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))
feature_spec, label_spec = ds.element_spec
for row, label in ds.take(1):
for name, value in row.items():
dtype = feature_spec[name].dtype.name
print(f"{name:<14} {dtype:<8} {value.numpy()}")
print(f"{'label':<14} {label_spec.dtype.name:<8} {label.numpy()}")
Output:
state string b'TX'
plan string b'basic'
tenure_months int64 3
monthly_usd float64 19.99
support_calls int64 4
label int64 1

tf.string and come back as bytes, while the numbers keep int64 and float64.Notice the b'TX': TensorFlow stores text as bytes, which you’ll need to decode if you go back to pandas.
Plain Python dicts work the same way, as you’ll see in converting a dictionary to a tensor in TensorFlow.
Shuffle and Batch the TensorFlow Dataset for Training
Keras trains on batches, not single rows. You shuffle first with a buffer as large as the data, then batch, then prefetch() so the next batch is ready while the model trains:
import os
os.environ.update(TF_CPP_MIN_LOG_LEVEL="3", TF_ENABLE_ONEDNN_OPTS="0")
import pandas as pd
import tensorflow as tf
tf.random.set_seed(42)
df = pd.read_csv("customers.csv")
labels = df.pop("churned")
ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))
train = ds.shuffle(len(df), seed=7).batch(3).prefetch(tf.data.AUTOTUNE)
for i, (batch, y) in enumerate(train, start=1):
print(f"batch {i}: {batch['state'].numpy()} labels {y.numpy()}")
even = ds.batch(3, drop_remainder=True)
print("batches with drop_remainder=True:", even.cardinality().numpy())
Output:
batch 1: [b'TX' b'NY' b'CA'] labels [0 0 0]
batch 2: [b'WA' b'FL' b'NY'] labels [0 1 0]
batch 3: [b'CA' b'TX'] labels [1 1]
batches with drop_remainder=True: 2

drop_remainder=True keeps only the two full ones.For caching, parallel map() and file-based input, see my tf.data pipelines tutorial.
Encode Categorical Pandas Columns for a Keras Model
A Dense layer can’t read b'TX'. The quickest pandas fix is one-hot encoding with get_dummies(), which gives you one float matrix:
import os
os.environ.update(TF_CPP_MIN_LOG_LEVEL="3", TF_ENABLE_ONEDNN_OPTS="0")
import pandas as pd
import tensorflow as tf
df = pd.read_csv("customers.csv")
labels = df.pop("churned")
X = pd.get_dummies(df, columns=["state", "plan"]).astype("float32")
print(X.shape, "->", list(X.columns[3:7]))
ds = tf.data.Dataset.from_tensor_slices((X.to_numpy(), labels.to_numpy()))
print(ds.element_spec[0])
Output:
(8, 11) -> ['state_CA', 'state_FL', 'state_NY', 'state_TX']
TensorSpec(shape=(11,), dtype=tf.float32, name=None)
The two text columns become eight 0/1 columns, so each element is a vector of 11 float32 inputs. In a test run, Keras model.fit() trained on this Dataset with no extra conversion.
To keep the encoding inside the model instead, Keras preprocessing layers handle it; I built that in structured data classification with Keras FeatureSpace.
Convert a Pandas DataFrame to a Tensor
Sometimes you’ll want one tensor, not a Dataset. For a DataFrame to tensor conversion, pick the numeric columns and call tf.convert_to_tensor():
import os
os.environ.update(TF_CPP_MIN_LOG_LEVEL="3", TF_ENABLE_ONEDNN_OPTS="0")
import pandas as pd
import tensorflow as tf
df = pd.read_csv("customers.csv")
nums = df[["tenure_months", "monthly_usd", "support_calls"]]
t = tf.convert_to_tensor(nums.to_numpy(dtype="float32"))
print(t.shape, t.dtype.name)
print(t[:2].numpy())
print("direct:", tf.convert_to_tensor(nums).dtype.name)
try:
tf.convert_to_tensor(df)
except ValueError as err:
print("ValueError:", err)
Output:
(8, 3) float32
[[ 3. 19.99 4. ]
[14. 49. 1. ]]
direct: float64
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).

Passing the numeric DataFrame straight in works too, but it stays float64. Lists follow the same rules, as in converting a list to a tensor.
Going the other way, loop over as_numpy_iterator() and decode the bytes; in my test the rebuilt DataFrame matched the CSV exactly. For single tensors, see converting a TensorFlow tensor to NumPy.
Errors You’ll See Converting a Pandas DataFrame to a Dataset
Real pandas exports have blanks, and most TensorFlow conversion errors trace back to them. Here’s the sample with one empty plan and one empty price:
import os
os.environ.update(TF_CPP_MIN_LOG_LEVEL="3", TF_ENABLE_ONEDNN_OPTS="0")
import numpy as np
import pandas as pd
import tensorflow as tf
df = pd.read_csv("customers.csv")
df.loc[2, "plan"] = None # a blank plan, like a real export
df.loc[5, "monthly_usd"] = None # and a blank price
labels = df.pop("churned")
try:
tf.data.Dataset.from_tensor_slices((dict(df), labels))
except ValueError as err:
print("1.", err)
prices = tf.data.Dataset.from_tensor_slices(df["monthly_usd"].to_numpy())
print("2. NaN slipped in:", any(np.isnan(p) for p in prices))
fixed = df.fillna({"plan": "unknown",
"monthly_usd": df["monthly_usd"].median()})
try:
tf.data.Dataset.from_tensor_slices((dict(fixed), labels[:7]))
except ValueError as err:
print("3.", str(err).splitlines()[0][:70])
ds = tf.data.Dataset.from_tensor_slices((dict(fixed), labels))
print("fixed rows:", ds.cardinality().numpy())
Output:
1. Failed to convert a NumPy array to a Tensor (Unsupported object type float).
2. NaN slipped in: True
3. Dimensions 8 and 7 are not compatible
fixed rows: 8