Skip to content

frames

Class info

Re-exported classes

Class Module Description
ArrowSource cutepandas.frames.arrowsource Read-only source over a pyarrow.Table (or RecordBatch).
ChunkCache cutepandas.frames.chunkcache Caches converted windows of a frame, keyed by (row block, column).
ColumnChunk cutepandas.frames.source A window of one column as Python values.
ColumnInfo cutepandas.frames.source Name and dtype of one column.
ColumnStats cutepandas.frames.source Basic statistics of one column (see FrameSource.describe).
EditableSource cutepandas.frames.source Optional hook: a source whose frame can be changed cell by cell (GUI thread).
FormatOptions cutepandas.frames.formatters How cell values are turned into display text.
FrameSource cutepandas.frames.source Read access to a rectangular frame, independent of the backend.
Kind cutepandas.frames.source Backend-independent family of a column dtype (drives formatting and icons).
PandasSource cutepandas.frames.pandassource Source over a pandas DataFrame (a Series is shown as a one-column frame).
PermutableSource cutepandas.frames.source Optional hook: sort order as row positions, and reads in any row order.
SortableSource cutepandas.frames.source Optional hook: a source that can return a sorted copy of its frame.

🛈 DocStrings

Backend-agnostic, Qt-free access to dataframes.

FrameSource is the protocol the Qt models of cutepandas are built on. as_source wraps a pandas DataFrame / Series, a pyarrow Table / RecordBatch or a polars DataFrame (polars is only imported when a polars frame is passed). Objects that already follow the protocol (e.g. a lazy source of an application) are returned unchanged.

ArrowSource

Read-only source over a pyarrow.Table (or RecordBatch).

Implements the optional SortableSource and PermutableSource hooks.

Source code in src/cutepandas/frames/arrowsource.py
class ArrowSource:
    """Read-only source over a `pyarrow.Table` (or `RecordBatch`).

    Implements the optional `SortableSource` and `PermutableSource` hooks.
    """

    backend = "pyarrow"

    def __init__(self, table: pa.Table | pa.RecordBatch):
        if isinstance(table, pa.RecordBatch):
            table = pa.Table.from_batches([table])
        self._table = table

    @property
    def native(self) -> pa.Table:
        return self._table

    @property
    def row_count(self) -> int:
        return self._table.num_rows

    @cached_property
    def columns(self) -> Sequence[ColumnInfo]:
        return [
            ColumnInfo(f.name, str(f.type), kind_for_arrow_type(f.type), f.type)
            for f in self._table.schema
        ]

    def fetch(self, start: int, stop: int, columns: Sequence[int]) -> list[ColumnChunk]:
        length = max(0, stop - start)
        return [_chunk(self._table.column(j).slice(start, length)) for j in columns]

    def fetch_rows(self, rows: np.ndarray, columns: Sequence[int]) -> list[ColumnChunk]:
        return [take_rows(self._table.column(j), rows) for j in columns]

    def fetch_arrow(self, start: int, stop: int, columns: Sequence[int]) -> pa.Table:
        return self._table.select(list(columns)).slice(start, max(0, stop - start))

    def null_count(self, column: int) -> int:
        return self._table.column(column).null_count

    def nbytes(self, column: int) -> int:
        return self._table.column(column).nbytes

    def value_range(self, column: int) -> tuple[float, float] | None:
        info = self.columns[column]
        if not (info.kind.is_numeric or info.kind == Kind.BOOLEAN):
            return None
        col = self._table.column(column)
        if info.kind == Kind.BOOLEAN:
            col = col.cast(pa.int8())
        result = pc.min_max(col)
        lo, hi = _scalar(result["min"]), _scalar(result["max"])
        if lo is None or hi is None:
            return None
        return float(lo), float(hi)

    def value_counts(
        self, column: int, limit: int | None = None
    ) -> list[tuple[Any, int]]:
        col = self._table.column(column)
        if col.null_count:
            col = col.drop_null()
        if not len(col):
            return []
        counts = pc.value_counts(col)
        values = counts.field("values").to_pylist()
        numbers = counts.field("counts").to_pylist()
        pairs = sorted(zip(values, numbers), key=lambda p: -p[1])
        return pairs if limit is None else pairs[:limit]

    def categories(self, column: int) -> list[Any] | None:
        col = self._table.column(column)
        if not pa.types.is_dictionary(col.type):
            return None
        if col.num_chunks == 0:
            return []
        return col.unify_dictionaries().chunk(0).dictionary.to_pylist()

    def describe(self, column: int, top: int = 10) -> ColumnStats:
        info = self.columns[column]
        col = self._table.column(column)
        lo = hi = mean = std = None
        if info.kind.is_numeric or info.kind.is_temporal or info.kind == Kind.STRING:
            result = pc.min_max(col)
            lo, hi = _scalar(result["min"]), _scalar(result["max"])
        if info.kind.is_numeric:
            mean = _scalar(pc.mean(col))
            std = _scalar(pc.stddev(col, ddof=1))
        if pa.types.is_dictionary(col.type):
            col = col.cast(col.type.value_type)
        try:
            unique = pc.count_distinct(col, mode="only_valid").as_py()
        except pa.ArrowNotImplementedError:  # e.g. nested types
            unique = None
        return ColumnStats(
            count=len(col),
            null_count=col.null_count,
            unique=unique,
            min=lo,
            max=hi,
            mean=None if mean is None else float(mean),
            std=None if std is None else float(std),
            top=self.value_counts(column, limit=top) if unique is not None else [],
        )

    def argsort(self, column: int, descending: bool = False) -> np.ndarray:
        return arrow_argsort(self._table.column(column), descending)

    def sort(self, column: int, descending: bool = False) -> pa.Table:
        return self._table.take(self.argsort(column, descending))

ChunkCache

Caches converted windows of a frame, keyed by (row block, column).

A row block covers chunk_rows consecutive rows of one column, so a wide frame only converts the visible columns. At most max_chunks blocks are kept; the least recently used one is dropped first, so memory stays bounded however far the user scrolls.

Every mutation happens under a lock, so a worker thread may fill the cache (get_or_build) while the GUI thread reads it. clear() and invalidate() start a new generation: a block built from the old data by a slow worker is dropped instead of stored.

Source code in src/cutepandas/frames/chunkcache.py
class ChunkCache[T]:
    """Caches converted windows of a frame, keyed by (row block, column).

    A row block covers `chunk_rows` consecutive rows of one column, so a wide frame only
    converts the visible columns. At most `max_chunks` blocks are kept; the least
    recently used one is dropped first, so memory stays bounded however far the user
    scrolls.

    Every mutation happens under a lock, so a worker thread may fill the cache
    (`get_or_build`) while the GUI thread reads it. `clear()` and `invalidate()` start a
    new generation: a block built from the old data by a slow worker is dropped instead
    of stored.
    """

    def __init__(self, chunk_rows: int = 256, max_chunks: int = 256):
        if chunk_rows < 1 or max_chunks < 1:
            msg = "chunk_rows and max_chunks must be positive"
            raise ValueError(msg)
        self.chunk_rows = chunk_rows
        self.max_chunks = max_chunks
        self._lock = threading.Lock()
        self._chunks: OrderedDict[tuple[int, int], T] = OrderedDict()
        self._generation = 0

    def __len__(self) -> int:
        with self._lock:
            return len(self._chunks)

    @property
    def generation(self) -> int:
        return self._generation

    def block_of(self, row: int) -> int:
        return row // self.chunk_rows

    def block_bounds(self, block: int, row_count: int) -> tuple[int, int]:
        """Row range (start, stop) of a block, clipped to `row_count`."""
        start = block * self.chunk_rows
        return start, min(start + self.chunk_rows, row_count)

    def get(self, block: int, column: int) -> T | None:
        key = (block, column)
        with self._lock:
            chunk = self._chunks.get(key)
            if chunk is not None:
                self._chunks.move_to_end(key)
            return chunk

    def put(
        self, block: int, column: int, chunk: T, generation: int | None = None
    ) -> bool:
        """Store a block; returns False if it was built for an older generation."""
        with self._lock:
            if generation is not None and generation != self._generation:
                return False
            self._chunks[block, column] = chunk
            self._chunks.move_to_end((block, column))
            while len(self._chunks) > self.max_chunks:
                self._chunks.popitem(last=False)
            return True

    def get_or_build(self, block: int, column: int, build: Callable[[int, int], T]) -> T:
        """Return the cached block or build it (outside the lock) and store it."""
        if (chunk := self.get(block, column)) is not None:
            return chunk
        generation = self._generation
        chunk = build(block, column)
        self.put(block, column, chunk, generation)
        return chunk

    def invalidate(self, *, block: int | None = None, column: int | None = None):
        """Drop the blocks of one row block and/or column (all if both are None)."""
        with self._lock:
            # A new generation also drops blocks that are being built right now.
            self._generation += 1
            if block is None and column is None:
                self._chunks.clear()
                return
            for key in list(self._chunks):
                if (block is None or key[0] == block) and (
                    column is None or key[1] == column
                ):
                    del self._chunks[key]

    def clear(self):
        """Drop everything and start a new generation (call when the frame changes)."""
        self.invalidate()

block_bounds

block_bounds(block: int, row_count: int) -> tuple[int, int]

Row range (start, stop) of a block, clipped to row_count.

Source code in src/cutepandas/frames/chunkcache.py
def block_bounds(self, block: int, row_count: int) -> tuple[int, int]:
    """Row range (start, stop) of a block, clipped to `row_count`."""
    start = block * self.chunk_rows
    return start, min(start + self.chunk_rows, row_count)

clear

clear()

Drop everything and start a new generation (call when the frame changes).

Source code in src/cutepandas/frames/chunkcache.py
def clear(self):
    """Drop everything and start a new generation (call when the frame changes)."""
    self.invalidate()

get_or_build

get_or_build(block: int, column: int, build: Callable[[int, int], T]) -> T

Return the cached block or build it (outside the lock) and store it.

Source code in src/cutepandas/frames/chunkcache.py
def get_or_build(self, block: int, column: int, build: Callable[[int, int], T]) -> T:
    """Return the cached block or build it (outside the lock) and store it."""
    if (chunk := self.get(block, column)) is not None:
        return chunk
    generation = self._generation
    chunk = build(block, column)
    self.put(block, column, chunk, generation)
    return chunk

invalidate

invalidate(*, block: int | None = None, column: int | None = None)

Drop the blocks of one row block and/or column (all if both are None).

Source code in src/cutepandas/frames/chunkcache.py
def invalidate(self, *, block: int | None = None, column: int | None = None):
    """Drop the blocks of one row block and/or column (all if both are None)."""
    with self._lock:
        # A new generation also drops blocks that are being built right now.
        self._generation += 1
        if block is None and column is None:
            self._chunks.clear()
            return
        for key in list(self._chunks):
            if (block is None or key[0] == block) and (
                column is None or key[1] == column
            ):
                del self._chunks[key]

put

put(block: int, column: int, chunk: T, generation: int | None = None) -> bool

Store a block; returns False if it was built for an older generation.

Source code in src/cutepandas/frames/chunkcache.py
def put(
    self, block: int, column: int, chunk: T, generation: int | None = None
) -> bool:
    """Store a block; returns False if it was built for an older generation."""
    with self._lock:
        if generation is not None and generation != self._generation:
            return False
        self._chunks[block, column] = chunk
        self._chunks.move_to_end((block, column))
        while len(self._chunks) > self.max_chunks:
            self._chunks.popitem(last=False)
        return True

ColumnChunk dataclass

A window of one column as Python values.

Source code in src/cutepandas/frames/source.py
@dataclass(frozen=True, slots=True)
class ColumnChunk:
    """A window of one column as Python values."""

    values: list[Any]
    """One Python value per row; missing values are None."""
    nulls: np.ndarray
    """Boolean mask, True where the value is missing."""

nulls instance-attribute

nulls: ndarray

Boolean mask, True where the value is missing.

values instance-attribute

values: list[Any]

One Python value per row; missing values are None.

ColumnInfo dataclass

Name and dtype of one column.

Source code in src/cutepandas/frames/source.py
@dataclass(frozen=True, slots=True)
class ColumnInfo:
    """Name and dtype of one column."""

    name: Any
    """Column label (a tuple for pandas MultiIndex columns)."""
    dtype: str
    """The backend dtype as text (`int64`, `string[pyarrow]`, `Datetime(...)`)."""
    kind: Kind
    native_dtype: Any = field(default=None, compare=False, repr=False)
    """The backend dtype object."""

    @property
    def label(self) -> str:
        return format_name(self.name)

dtype instance-attribute

dtype: str

The backend dtype as text (int64, string[pyarrow], Datetime(...)).

name instance-attribute

name: Any

Column label (a tuple for pandas MultiIndex columns).

native_dtype class-attribute instance-attribute

native_dtype: Any = field(default=None, compare=False, repr=False)

The backend dtype object.

ColumnStats dataclass

Basic statistics of one column (see FrameSource.describe).

Source code in src/cutepandas/frames/source.py
@dataclass(frozen=True, slots=True)
class ColumnStats:
    """Basic statistics of one column (see `FrameSource.describe`)."""

    count: int
    null_count: int
    unique: int | None = None
    min: Any = None
    max: Any = None
    mean: float | None = None
    std: float | None = None
    top: list[tuple[Any, int]] = field(default_factory=list)
    """Most frequent non-null values with their counts, most frequent first."""

top class-attribute instance-attribute

top: list[tuple[Any, int]] = field(default_factory=list)

Most frequent non-null values with their counts, most frequent first.

EditableSource

Bases: Protocol

Optional hook: a source whose frame can be changed cell by cell (GUI thread).

Source code in src/cutepandas/frames/source.py
@runtime_checkable
class EditableSource(Protocol):
    """Optional hook: a source whose frame can be changed cell by cell (GUI thread)."""

    def set_value(self, row: int, column: int, value: Any) -> None:
        """Change one cell in place; raises on invalid values."""
        ...

set_value

set_value(row: int, column: int, value: Any) -> None

Change one cell in place; raises on invalid values.

Source code in src/cutepandas/frames/source.py
def set_value(self, row: int, column: int, value: Any) -> None:
    """Change one cell in place; raises on invalid values."""
    ...

FormatOptions dataclass

How cell values are turned into display text.

Source code in src/cutepandas/frames/formatters.py
@dataclass(frozen=True, slots=True)
class FormatOptions:
    """How cell values are turned into display text."""

    float_precision: int = 6
    """Significant digits for floats (`{:.6g}`, whole numbers keep a `.0`)."""
    thousands_separator: bool = False
    """Group digits of integers and floats (`1,234,567`)."""
    null_text: str = ""
    """Text shown for missing values."""
    max_text_length: int = 200
    """Longer texts are cut and end with an ellipsis (the tooltip shows all)."""

float_precision class-attribute instance-attribute

float_precision: int = 6

Significant digits for floats ({:.6g}, whole numbers keep a .0).

max_text_length class-attribute instance-attribute

max_text_length: int = 200

Longer texts are cut and end with an ellipsis (the tooltip shows all).

null_text class-attribute instance-attribute

null_text: str = ''

Text shown for missing values.

thousands_separator class-attribute instance-attribute

thousands_separator: bool = False

Group digits of integers and floats (1,234,567).

FrameSource

Bases: Protocol

Read access to a rectangular frame, independent of the backend.

Source code in src/cutepandas/frames/source.py
@runtime_checkable
class FrameSource(Protocol):
    """Read access to a rectangular frame, independent of the backend."""

    backend: str
    """Short backend name: `pandas`, `pyarrow` or `polars`."""

    @property
    def native(self) -> Any:
        """The wrapped backend frame."""
        ...

    @property
    def row_count(self) -> int: ...

    @property
    def columns(self) -> Sequence[ColumnInfo]: ...

    def fetch(self, start: int, stop: int, columns: Sequence[int]) -> list[ColumnChunk]:
        """Rows `start:stop` of the given column positions as Python values."""
        ...

    def fetch_arrow(self, start: int, stop: int, columns: Sequence[int]) -> pa.Table:
        """Rows `start:stop` of the given column positions as an Arrow table."""
        ...

    def null_count(self, column: int) -> int: ...

    def nbytes(self, column: int) -> int:
        """Memory used by the column's buffers (backend estimate)."""
        ...

    def value_range(self, column: int) -> tuple[float, float] | None:
        """(min, max) of a numeric or boolean column, None for other kinds / no data."""
        ...

    def value_counts(
        self, column: int, limit: int | None = None
    ) -> list[tuple[Any, int]]:
        """Non-null values with their counts, most frequent first."""
        ...

    def categories(self, column: int) -> list[Any] | None:
        """Categories of a categorical / enum / dictionary column, else None."""
        ...

    def describe(self, column: int, top: int = 10) -> ColumnStats:
        """Basic statistics of one column.

        Scans the whole column: call it off the GUI thread for large frames.
        """
        ...

backend instance-attribute

backend: str

Short backend name: pandas, pyarrow or polars.

native property

native: Any

The wrapped backend frame.

categories

categories(column: int) -> list[Any] | None

Categories of a categorical / enum / dictionary column, else None.

Source code in src/cutepandas/frames/source.py
def categories(self, column: int) -> list[Any] | None:
    """Categories of a categorical / enum / dictionary column, else None."""
    ...

describe

describe(column: int, top: int = 10) -> ColumnStats

Basic statistics of one column.

Scans the whole column: call it off the GUI thread for large frames.

Source code in src/cutepandas/frames/source.py
def describe(self, column: int, top: int = 10) -> ColumnStats:
    """Basic statistics of one column.

    Scans the whole column: call it off the GUI thread for large frames.
    """
    ...

fetch

fetch(start: int, stop: int, columns: Sequence[int]) -> list[ColumnChunk]

Rows start:stop of the given column positions as Python values.

Source code in src/cutepandas/frames/source.py
def fetch(self, start: int, stop: int, columns: Sequence[int]) -> list[ColumnChunk]:
    """Rows `start:stop` of the given column positions as Python values."""
    ...

fetch_arrow

fetch_arrow(start: int, stop: int, columns: Sequence[int]) -> Table

Rows start:stop of the given column positions as an Arrow table.

Source code in src/cutepandas/frames/source.py
def fetch_arrow(self, start: int, stop: int, columns: Sequence[int]) -> pa.Table:
    """Rows `start:stop` of the given column positions as an Arrow table."""
    ...

nbytes

nbytes(column: int) -> int

Memory used by the column's buffers (backend estimate).

Source code in src/cutepandas/frames/source.py
def nbytes(self, column: int) -> int:
    """Memory used by the column's buffers (backend estimate)."""
    ...

value_counts

value_counts(column: int, limit: int | None = None) -> list[tuple[Any, int]]

Non-null values with their counts, most frequent first.

Source code in src/cutepandas/frames/source.py
def value_counts(
    self, column: int, limit: int | None = None
) -> list[tuple[Any, int]]:
    """Non-null values with their counts, most frequent first."""
    ...

value_range

value_range(column: int) -> tuple[float, float] | None

(min, max) of a numeric or boolean column, None for other kinds / no data.

Source code in src/cutepandas/frames/source.py
def value_range(self, column: int) -> tuple[float, float] | None:
    """(min, max) of a numeric or boolean column, None for other kinds / no data."""
    ...

Kind

Bases: StrEnum

Backend-independent family of a column dtype (drives formatting and icons).

Source code in src/cutepandas/frames/source.py
class Kind(enum.StrEnum):
    """Backend-independent family of a column dtype (drives formatting and icons)."""

    INTEGER = "integer"
    FLOAT = "float"
    DECIMAL = "decimal"
    BOOLEAN = "boolean"
    STRING = "string"
    CATEGORICAL = "categorical"
    DATETIME = "datetime"
    DATE = "date"
    TIME = "time"
    DURATION = "duration"
    BINARY = "binary"
    NESTED = "nested"
    NULL = "null"
    OBJECT = "object"

    @property
    def is_numeric(self) -> bool:
        return self in {Kind.INTEGER, Kind.FLOAT, Kind.DECIMAL}

    @property
    def is_temporal(self) -> bool:
        return self in {Kind.DATETIME, Kind.DATE, Kind.TIME, Kind.DURATION}

PandasSource

Source over a pandas DataFrame (a Series is shown as a one-column frame).

Supports every pandas dtype, incl. pyarrow-backed ones (string[pyarrow], pd.ArrowDtype). Implements the optional SortableSource, PermutableSource and EditableSource hooks: set_value writes in place (DataFrame.iat).

Source code in src/cutepandas/frames/pandassource.py
class PandasSource:
    """Source over a pandas DataFrame (a Series is shown as a one-column frame).

    Supports every pandas dtype, incl. pyarrow-backed ones (`string[pyarrow]`,
    `pd.ArrowDtype`). Implements the optional `SortableSource`, `PermutableSource` and
    `EditableSource` hooks: `set_value` writes in place (`DataFrame.iat`).
    """

    backend = "pandas"

    def __init__(self, df: pd.DataFrame | pd.Series):
        self._df = df.to_frame() if isinstance(df, pd.Series) else df

    @property
    def native(self) -> pd.DataFrame:
        return self._df

    @property
    def row_count(self) -> int:
        return len(self._df)

    @cached_property
    def columns(self) -> Sequence[ColumnInfo]:
        return [
            ColumnInfo(name, str(dtype), kind_for_pandas_dtype(dtype), dtype)
            for name, dtype in zip(self._df.columns, self._df.dtypes)
        ]

    def _column(self, column: int) -> pd.Series:
        return self._df.iloc[:, column]

    def fetch(self, start: int, stop: int, columns: Sequence[int]) -> list[ColumnChunk]:
        window = self._df.iloc[start:stop]  # a view (copy-on-write)
        return [_chunk(window.iloc[:, j]) for j in columns]

    def fetch_rows(self, rows: np.ndarray, columns: Sequence[int]) -> list[ColumnChunk]:
        chunks = []
        for j in columns:
            series = self._column(j)
            if _is_arrow_backed(series.dtype):
                # pandas' take on a chunked Arrow array concatenates all chunks
                chunks.append(take_rows(pa.array(series.array), rows))
            else:
                chunks.append(_chunk(series.iloc[rows]))
        return chunks

    def fetch_arrow(self, start: int, stop: int, columns: Sequence[int]) -> pa.Table:
        window = self._df.iloc[start:stop, list(columns)]
        names = [str(c) for c in window.columns]
        arrays = [pa.array(window.iloc[:, j]) for j in range(window.shape[1])]
        return pa.table(arrays, names=names)

    def null_count(self, column: int) -> int:
        return int(self._column(column).isna().sum())

    def nbytes(self, column: int) -> int:
        return int(self._column(column).nbytes)

    def value_range(self, column: int) -> tuple[float, float] | None:
        info = self.columns[column]
        if not (info.kind.is_numeric or info.kind == Kind.BOOLEAN):
            return None
        series = self._column(column)
        if ptypes.is_complex_dtype(series.dtype):
            series = series.abs()
        try:
            lo, hi = _python(series.min()), _python(series.max())
        except TypeError:
            return None
        if lo is None or hi is None:
            return None
        return float(lo), float(hi)

    def value_counts(
        self, column: int, limit: int | None = None
    ) -> list[tuple[Any, int]]:
        counts = self._column(column).value_counts(dropna=True, sort=True)
        if limit is not None:
            counts = counts.head(limit)
        return [(_python(k), int(v)) for k, v in counts.items()]

    def categories(self, column: int) -> list[Any] | None:
        dtype = self._column(column).dtype
        if isinstance(dtype, pd.CategoricalDtype):
            return [_python(c) for c in dtype.categories]
        if isinstance(dtype, pd.ArrowDtype) and pa.types.is_dictionary(
            dtype.pyarrow_dtype
        ):
            return _arrow_dictionary(self._column(column))
        return None

    def describe(self, column: int, top: int = 10) -> ColumnStats:
        info = self.columns[column]
        series = self._column(column)
        lo = hi = mean = std = None
        orderable = info.kind.is_numeric or info.kind.is_temporal
        if orderable or info.kind == Kind.STRING:
            try:
                lo, hi = _python(series.min()), _python(series.max())
            except TypeError:
                lo = hi = None
        if info.kind.is_numeric and not ptypes.is_complex_dtype(series.dtype):
            mean, std = _python(series.mean()), _python(series.std())
        try:
            unique = int(series.nunique(dropna=True))
        except TypeError:  # unhashable objects
            unique = None
        return ColumnStats(
            count=len(series),
            null_count=int(series.isna().sum()),
            unique=unique,
            min=lo,
            max=hi,
            mean=None if mean is None else float(mean),
            std=None if std is None else float(std),
            top=self.value_counts(column, limit=top) if unique is not None else [],
        )

    def argsort(self, column: int, descending: bool = False) -> np.ndarray:
        # By position (labels are ambiguous for duplicate columns) and stable, so
        # sorting by one column after another keeps the earlier order for ties.
        series = self._column(column)
        dtype = series.dtype
        if _is_arrow_backed(dtype):
            # Arrow-backed (the default `str` dtype of pandas 3): Arrow's sort kernel,
            # on the column's own buffers (no conversion).
            return arrow_argsort(pa.array(series.array), descending)
        if isinstance(dtype, np.dtype) and dtype.kind in "biufmM":
            return numpy_argsort(series.to_numpy(copy=False), descending)
        if not descending:
            positions = series.argsort(kind="stable").to_numpy()  # NaN last
        else:
            # argsort can't sort descending; this keeps ties stable and NaN last
            ranked = series.reset_index(drop=True)
            ranked = ranked.sort_values(ascending=False, kind="stable")
            positions = ranked.index.to_numpy()
        return np.asarray(positions, dtype=np.intp)

    def sort(self, column: int, descending: bool = False) -> pd.DataFrame:
        return self._df.take(self.argsort(column, descending))

    def set_value(self, row: int, column: int, value: Any) -> None:
        self._df.iat[row, column] = value

PermutableSource

Bases: Protocol

Optional hook: sort order as row positions, and reads in any row order.

Used for a display-only sort: the model keeps the permutation (one integer per row) and reads each visible window through it, so the frame is never copied.

Source code in src/cutepandas/frames/source.py
@runtime_checkable
class PermutableSource(Protocol):
    """Optional hook: sort order as row positions, and reads in any row order.

    Used for a display-only sort: the model keeps the permutation (one integer per
    row) and reads each visible window through it, so the frame is never copied.
    """

    def argsort(self, column: int, descending: bool = False) -> np.ndarray:
        """Row positions that sort the frame stably by one column, nulls last."""
        ...

    def fetch_rows(self, rows: np.ndarray, columns: Sequence[int]) -> list[ColumnChunk]:
        """The given row positions (in that order) of the given columns."""
        ...

argsort

argsort(column: int, descending: bool = False) -> ndarray

Row positions that sort the frame stably by one column, nulls last.

Source code in src/cutepandas/frames/source.py
def argsort(self, column: int, descending: bool = False) -> np.ndarray:
    """Row positions that sort the frame stably by one column, nulls last."""
    ...

fetch_rows

fetch_rows(rows: ndarray, columns: Sequence[int]) -> list[ColumnChunk]

The given row positions (in that order) of the given columns.

Source code in src/cutepandas/frames/source.py
def fetch_rows(self, rows: np.ndarray, columns: Sequence[int]) -> list[ColumnChunk]:
    """The given row positions (in that order) of the given columns."""
    ...

SortableSource

Bases: Protocol

Optional hook: a source that can return a sorted copy of its frame.

Source code in src/cutepandas/frames/source.py
@runtime_checkable
class SortableSource(Protocol):
    """Optional hook: a source that can return a sorted copy of its frame."""

    def sort(self, column: int, descending: bool = False) -> Any:
        """Return a new native frame, sorted stably by one column, nulls last."""
        ...

sort

sort(column: int, descending: bool = False) -> Any

Return a new native frame, sorted stably by one column, nulls last.

Source code in src/cutepandas/frames/source.py
def sort(self, column: int, descending: bool = False) -> Any:
    """Return a new native frame, sorted stably by one column, nulls last."""
    ...

as_source

as_source(obj: Any) -> FrameSource

Wrap a supported frame in its FrameSource adapter.

Source code in src/cutepandas/frames/__init__.py
def as_source(obj: Any) -> FrameSource:
    """Wrap a supported frame in its `FrameSource` adapter."""
    if isinstance(obj, pd.DataFrame | pd.Series):
        return PandasSource(obj)
    if isinstance(obj, pa.Table | pa.RecordBatch):
        return ArrowSource(obj)
    if is_polars_frame(obj):
        from cutepandas.frames.polarssource import PolarsSource

        return PolarsSource(obj)
    if isinstance(obj, FrameSource):
        return obj
    msg = f"Unsupported frame type: {type(obj).__qualname__}"
    raise TypeError(msg)

format_chunk

format_chunk(values: list[Any], nulls: ndarray, formatter: Formatter, null_text: str) -> list[str]

Format a chunk of values; missing values become null_text.

Source code in src/cutepandas/frames/formatters.py
def format_chunk(
    values: list[Any], nulls: np.ndarray, formatter: Formatter, null_text: str
) -> list[str]:
    """Format a chunk of values; missing values become `null_text`."""
    if nulls.any():
        return [
            null_text if is_null else formatter(value)
            for value, is_null in zip(values, nulls.tolist())
        ]
    return [formatter(value) for value in values]

format_name

format_name(name: Any, separator: str = ' | ') -> str

Column label as text; tuples (pandas MultiIndex columns) are joined.

Source code in src/cutepandas/frames/source.py
def format_name(name: Any, separator: str = " | ") -> str:
    """Column label as text; tuples (pandas MultiIndex columns) are joined."""
    if isinstance(name, tuple | list):
        return separator.join(str(i) for i in name)
    return str(name)

formatter_for

formatter_for(kind: Kind, options: FormatOptions) -> Formatter

Return a function that formats one non-null value of the given kind.

Source code in src/cutepandas/frames/formatters.py
def formatter_for(kind: Kind, options: FormatOptions) -> Formatter:
    """Return a function that formats one non-null value of the given kind."""
    limit = options.max_text_length
    sep = "," if options.thousands_separator else ""
    match kind:
        case Kind.FLOAT:
            spec = f"{sep}.{options.float_precision}g"

            def fmt_float(value: Any) -> str:
                if not isinstance(value, float):
                    return str(value)  # complex
                if math.isnan(value):
                    return "NaN"
                text = format(value, spec)
                # keep floats recognisable: 3.0 -> "3.0", not "3"
                return text if any(c in text for c in ".eni") else text + ".0"

            return fmt_float
        case Kind.INTEGER if sep:
            return lambda value: format(value, sep)
        case Kind.INTEGER | Kind.DECIMAL:
            return str
        case Kind.STRING | Kind.CATEGORICAL | Kind.OBJECT | Kind.NESTED | Kind.BINARY:
            return lambda value: _truncate(str(value), limit)
        case _:
            return str

is_polars_frame

is_polars_frame(obj: Any) -> bool

True for a polars DataFrame, without importing polars.

Source code in src/cutepandas/frames/__init__.py
def is_polars_frame(obj: Any) -> bool:
    """True for a polars DataFrame, without importing polars."""
    cls = type(obj)
    return cls.__module__.startswith("polars") and cls.__name__ == "DataFrame"

kind_for_arrow_type

kind_for_arrow_type(typ: DataType) -> Kind

Map an Arrow type to a Kind.

Source code in src/cutepandas/frames/arrowsource.py
def kind_for_arrow_type(typ: pa.DataType) -> Kind:
    """Map an Arrow type to a `Kind`."""
    t = pa.types
    if t.is_dictionary(typ):
        return Kind.CATEGORICAL
    if t.is_boolean(typ):
        return Kind.BOOLEAN
    if t.is_integer(typ):
        return Kind.INTEGER
    if t.is_floating(typ):
        return Kind.FLOAT
    if t.is_decimal(typ):
        return Kind.DECIMAL
    if t.is_string(typ) or t.is_large_string(typ) or t.is_string_view(typ):
        return Kind.STRING
    if t.is_timestamp(typ):
        return Kind.DATETIME
    if t.is_date(typ):
        return Kind.DATE
    if t.is_time(typ):
        return Kind.TIME
    if t.is_duration(typ):
        return Kind.DURATION
    if t.is_binary(typ) or t.is_large_binary(typ) or t.is_fixed_size_binary(typ):
        return Kind.BINARY
    if t.is_null(typ):
        return Kind.NULL
    if t.is_nested(typ):
        return Kind.NESTED
    return Kind.OBJECT

kind_for_pandas_dtype

kind_for_pandas_dtype(dtype: Any) -> Kind

Map a pandas / NumPy dtype (incl. pd.ArrowDtype, or its name) to a Kind.

Source code in src/cutepandas/frames/pandassource.py
def kind_for_pandas_dtype(dtype: Any) -> Kind:
    """Map a pandas / NumPy dtype (incl. `pd.ArrowDtype`, or its name) to a `Kind`."""
    if isinstance(dtype, str):
        dtype = ptypes.pandas_dtype(dtype)
    if isinstance(dtype, pd.ArrowDtype):
        return kind_for_arrow_type(dtype.pyarrow_dtype)
    if isinstance(dtype, pd.CategoricalDtype):
        return Kind.CATEGORICAL
    if ptypes.is_bool_dtype(dtype):
        return Kind.BOOLEAN
    if ptypes.is_integer_dtype(dtype):
        return Kind.INTEGER
    if ptypes.is_float_dtype(dtype) or ptypes.is_complex_dtype(dtype):
        return Kind.FLOAT
    if ptypes.is_datetime64_any_dtype(dtype) or isinstance(dtype, pd.PeriodDtype):
        return Kind.DATETIME
    if ptypes.is_timedelta64_dtype(dtype):
        return Kind.DURATION
    if isinstance(dtype, pd.StringDtype):
        return Kind.STRING
    return Kind.OBJECT