pola-rs/polars · error · ValueError
`label` and `features` only apply when `return_type` is 'dat
Error message
`label` and `features` only apply when `return_type` is 'dataset' or 'dict'
What it means
Raised by DataFrame.to_torch when `label` or `features` is supplied but `return_type` is not 'dataset' or 'dict'. Label/features splitting exists only for those two exports: 'dataset' builds a PolarsDataset with labeled features and 'dict' returns {'label': tensor, 'features': tensor}. The default 'tensor' export returns one tensor of the whole frame, so there is no slot for a separate label.
Source
Thrown at py-polars/src/polars/dataframe/frame.py:2470
>>> housing = fetch_california_housing() # doctest: +SKIP
>>> df = pl.DataFrame(
... data=housing.data,
... schema=housing.feature_names,
... ).with_columns(
... Target=housing.target,
... ) # doctest: +SKIP
>>> train = df.to_torch("dataset", label="Target") # doctest: +SKIP
>>> loader = DataLoader(
... train,
... shuffle=True,
... batch_size=64,
... ) # doctest: +SKIP
"""
if return_type not in ("dataset", "dict") and (
label is not None or features is not None
):
msg = "`label` and `features` only apply when `return_type` is 'dataset' or 'dict'"
raise ValueError(msg)
elif return_type == "dict" and label is None and features is not None:
msg = "`label` is required if setting `features` when `return_type='dict'"
raise ValueError(msg)
torch = import_optional("torch")
# Cast columns.
if dtype in (UInt16, UInt32, UInt64):
msg = f"PyTorch does not support u16, u32, or u64 dtypes; given {dtype}"
raise ValueError(msg)
to_dtype = dtype or {UInt16: Int32, UInt32: Int64, UInt64: Int64}
if label is not None:
label_frame = self.select(label)
# Avoid casting the label if it's an expression.
if not isinstance(label, pl.Expr):
label_frame = label_frame.cast(to_dtype) # type: ignore[arg-type]View on GitHub (pinned to df599052da)
Solutions
- Use return_type='dataset' for DataLoader training: `df.to_torch('dataset', label='target')`
- Or 'dict' for raw tensors: `df.to_torch('dict', label='target', features=['f1'])`
- Or drop label/features and export the whole frame as one tensor: `df.to_torch()`
Example fix
# before
train = df.to_torch(label='target')
# after
train = df.to_torch('dataset', label='target')
loader = DataLoader(train, batch_size=64) Defensive patterns
Strategy: validation
Validate before calling
if (label is not None or features is not None) and return_type not in ('dataset', 'dict'):
raise ValueError('to_torch: label/features require return_type "dataset" or "dict"')
out = df.to_torch(return_type, label=label, features=features) Try / catch
try:
out = df.to_torch(return_type, label=label, features=features)
except ValueError as e:
if 'only apply when' in str(e):
out = df.to_torch('dataset', label=label, features=features)
else:
raise Prevention
- Default to to_torch('dataset', label=...) for DataLoader workflows
- Remember the default return_type is 'tensor', which forbids label/features
- Validate the (return_type, label, features) triple in shared export helpers
When it happens
Trigger: `df.to_torch('tensor', label='y')`, `df.to_torch(label='target')` (default return_type is 'tensor'), or any call with label/features and return_type='tensor'.
Common situations: Writing a DataLoader pipeline and forgetting to switch the first argument to 'dataset'; refactoring from to_jax('dict', ...) to to_torch and keeping label but not the return_type; tutorial code adapted with label added but default return_type left in place.
Related errors
- `label` and `features` only apply when `return_type` is 'dic
- `label` is required if setting `features` when `return_type=
- invalid `return_type`: {return_type!r} Expected one of: {val
- invalid `return_type`: {return_type!r} Expected one of: {val
- PyTorch does not support u16, u32, or u64 dtypes; given {dty
AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16).
Data as JSON: /api/errors/8d2e2ff21f33214d.
Report an issue: GitHub.