polars.from_torch#

polars.from_torch(
tensor: torch.Tensor,
schema: SchemaDefinition | None = None,
*,
schema_overrides: SchemaDict | None = None,
orient: Orientation | None = None,
force: bool = False,
) → DataFrame[source]#

Construct a DataFrame from a PyTorch Tensor.

Parameters:
tensortorch.Tensor

A PyTorch Tensor object of one or more dimensions.

schemaSequence of str, (str,DataType) pairs, or a {str:DataType,} dict

The DataFrame schema may be declared in several ways:

  • As a dict of {name:type} pairs; if type is None, it will be auto-inferred.

  • As a list of column names; in this case types are automatically inferred.

  • As a list of (name,type) pairs; this is equivalent to the dictionary form.

If you supply a list of column names that does not match the names in the underlying data, the names given here will overwrite them. The number of names given in the schema should match the underlying data dimensions.

schema_overridesdict, default None

Support type specification or override of one or more columns; note that any dtypes inferred from the columns param will be overridden.

orient{None, ‘col’, ‘row’}

Whether to interpret two-dimensional data as columns or as rows. If None, the orientation is inferred by matching the columns and data dimensions. If this does not yield conclusive results, column orientation is used.

forcebool

If False, the conversion is performed only if the Tensor is on CPU, does not require grad, does not have its conjugate bit set, and is of a dtype (and layout) that NumPy supports; this will typically be zero-copy. If True, it is equivalent to calling .detach().cpu().resolve_conj().resolve_neg() before passing the Tensor to Polars.

Returns:
DataFrame

Examples

>>> import torch
>>> data = torch.tensor(
...     [
...         [1234.5, 200.0, 3000.5],
...         [8000.0, 500.5, 6000.0],
...     ]
... )
>>> df = pl.from_torch(
...     data,
...     schema=["colx", "coly", "colz"],
...     schema_overrides={"colz": pl.Float64},
... )
>>> df
shape: (2, 3)
┌────────┬───────┬────────┐
│ colx   ┆ coly  ┆ colz   │
│ ---    ┆ ---   ┆ ---    │
│ f32    ┆ f32   ┆ f64    │
╞════════╪═══════╪════════╡
│ 1234.5 ┆ 200.0 ┆ 3000.5 │
│ 8000.0 ┆ 500.5 ┆ 6000.0 │
└────────┴───────┴────────┘