Skip to content

DataFrame

DataFrame

Bases: _DataFrameFields, _Base

columns property

columns: list[Column]

schema property

schema: StructType

dtypes property

dtypes: list[tuple[str, str]]

List of (column_name, type_string) tuples for the underlying DataFrame.

write property

writeStream property

writeStream: DataStreamWriter

generate_schema classmethod

generate_schema()

columndict

columndict() -> dict[str, Column]

to_spark

to_spark() -> DataFrame

to_df

to_df() -> DataFrame

from_df classmethod

from_df(
    df: DataFrame,
    alias: str | None = None,
    disable_select: bool = False,
) -> Self
from_df(
    df: DataFrame,
    alias: str | None = None,
    disable_select: bool = False,
) -> Self
from_df(
    df: DataFrame | DataFrame,
    alias: str | None = None,
    disable_select: bool = False,
) -> Self

Wrap a raw Spark DataFrame into a typed instance.

Validates that all required columns exist, applies defaults for missing columns, and optionally narrows the DataFrame to only declared columns.

lazy classmethod

lazy(alias: str | None = None) -> Self

Column-only handle: a typed instance with no underlying DataFrame.

For building column expressions (join / merge / filter conditions) without materializing or referencing data — the typed analog of a bare F.col(...). With alias, columns resolve to col("<alias>.<field>"); without it, to col("<field>"), matching from_df(alias=...) exactly.

Any operation that touches the data (to_df, to_spark, filter, select, show, ...) raises LazyDataFrameError — this handle has no DataFrame by design.

create classmethod

create(
    data: Iterable[Any], spark: SparkSession | None = None
) -> Self

Create a typed instance from local data.

Shorthand for cls.from_df(spark.createDataFrame(data, schema)) where the schema is derived from the class. data may be dicts / Rows (matched by Spark column name), tuples / lists (positional), or a pandas DataFrame. spark defaults to the active session.

Defaults are Spark expressions, so they are applied by from_df for columns absent from the data:

  • dicts / Rows: a column is provided if any row has the key; rows missing a key of a provided column get null, not the default.
  • tuples: length must match either all columns (defaults overridden) or only the columns without defaults, in declaration order.

select

select(*cols: str | Column | Column[Any]) -> DataFrame

Project a set of columns, returning a new untyped DataFrame.

Beyond standard column projection, select handles two TypeSpark-specific patterns automatically:

  • Group-by aggregation: if any column is wrapped with .group() and at least one aggregate function (e.g. sum, count) is included, the call is promoted to a .groupBy().agg() under the hood.
  • Deferred / explode columns: columns produced by Array.explode() are materialised in a two-step select so that the exploded values are available for subsequent projection.

withColumn

withColumn(colName: str, col: Column | Column) -> DataFrame

Add a column outside the model, returning an untyped DataFrame.

For an exploded column use tsf.explode(arr); arr.explode(...) builds model columns and belongs in the constructor.

drop

drop(*cols: str | Column | Column) -> DataFrame

drop_duplicates

drop_duplicates(subset: list[Column] | None = None) -> Self

dropDuplicates

dropDuplicates(subset: list[Column] | None = None) -> Self

distinct

distinct() -> Self

filter

filter(
    condition: Callable[[Self], Column[BooleanType]],
) -> Self
filter(
    condition: str | Column | Column[BooleanType],
) -> Self
filter(
    condition: str
    | Column
    | Column[BooleanType]
    | Callable[[Self], Column[BooleanType]],
) -> Self

where

where(
    condition: str | Column | Column[BooleanType],
) -> Self

qualify

qualify(condition: Column | Column[BooleanType]) -> Self

Filter rows on a window-function expression, like SQL QUALIFY.

Spark's DataFrame filter cannot reference window functions directly. qualify materialises the boolean expression into a temporary column, filters on it, then drops it — so window-based predicates work in one call::

w = ts.Window.partitionBy(frame.x).orderBy(frame.y)
frame.qualify(tsf.row_number().over(w) == 1)

Schema is unchanged (the temporary column is dropped).

orderBy

orderBy(*cols: Column[Any] | Column, **kwargs: Any) -> Self

sort

sort(*cols: Column[Any] | Column, **kwargs: Any) -> Self

limit

limit(num: int) -> Self

coalesce

coalesce(numPartitions: int) -> Self

repartition

repartition(
    numPartitions: int, *cols: Column[Any] | Column
) -> Self

cache

cache() -> Self

persist

persist(storageLevel: Any | None = None) -> Self

unpersist

unpersist(blocking: bool = False) -> Self

sample

sample(
    withReplacement: bool = False,
    fraction: float = 0.5,
    seed: int | None = None,
) -> Self

alias

alias(alias: str) -> Self

Create an aliased copy of this DataFrame for use in joins.

Prefixes all column references with alias so that columns from two instances of the same schema can be distinguished.

union

union(other: Self) -> Self
union(
    other: DataFrame, allowMissingColumns: bool = False
) -> DataFrame
union(
    other: Self | DataFrame,
    allowMissingColumns: bool = False,
) -> Self | DataFrame

Union this DataFrame with another by column name.

Delegates to unionByName rather than positional union.

Return type depends on other:

  • Same concrete class → returns Self (typed schema preserved).
  • Plain DataFrame → returns untyped DataFrame.

Set allowMissingColumns=True to union DataFrames with different column sets (missing columns are filled with null).

join

join(
    other: DataFrame | DataFrame,
    on: Column | str | list[str] | Column | None = None,
    how: JoinType | None = None,
) -> DataFrame

Join with another DataFrame, returning an untyped DataFrame.

The result is untyped because the combined schema depends on the join type and the schemas of both sides.

crossJoin

crossJoin(other: DataFrame | DataFrame) -> DataFrame

Cartesian product with another DataFrame, returning an untyped DataFrame.

The result is untyped because the combined schema depends on the schemas of both sides.

leftsemi

leftsemi(
    other: DataFrame | DataFrame,
    on: Column | str | list[str] | Column | None = None,
) -> Self

Filter rows using a left semi join, preserving this DataFrame's typed schema.

leftanti

leftanti(
    other: DataFrame | DataFrame,
    on: Column | str | list[str] | Column | None = None,
) -> Self

Filter rows using a left anti join, preserving this DataFrame's typed schema.

broadcast

broadcast() -> Self

withWatermark

withWatermark(
    eventTime: Column[TimestampType], delayThreshold: str
) -> Self

show

show(
    n: int = 20,
    truncate: bool = True,
    vertical: bool = False,
) -> None

count

count() -> int

collect

collect() -> list[Row]

first

first() -> Row | None

toPandas

toPandas()

printSchema

printSchema() -> None

createOrReplaceTempView

createOrReplaceTempView(name: str) -> None

createTempView

createTempView(name: str) -> None