Skip to content

pandasmodels

Class info

Re-exported classes

Class Module Description
CategoryModel cutepandas.pandasmodels.categorymodel One row per category of a column, with its code and number of rows, read-only.
CellChunk cutepandas.pandasmodels.dataframemodel One converted block of a column: everything data() returns, per row.
DataFrameHolder cutepandas.pandasmodels.dataframeholder Holds the current frame for several models / widgets (GUI thread only).
DataFrameModel cutepandas.pandasmodels.dataframemodel Virtual table model for pandas, pyarrow and polars frames.
HorizontalHeaderModel cutepandas.pandasmodels.dataframemodel Column labels: one row per pandas column level; one row for other backends.
PandasCategoryListModel cutepandas.pandasmodels.pandascategorylistmodel CategoryModel for a pandas category column that also edits it.
PandasColumnListModel cutepandas.pandasmodels.pandascolumnlistmodel SchemaModel for pandas frames that also edits them.
PandasEvalFilterProxyModel cutepandas.pandasmodels.pandasindexfilterproxymodel Filters a DataFrame by a boolean DataFrame.eval expression, like 'a > 10'.
PandasIndexListModel cutepandas.pandasmodels.pandascolumnlistmodel Index levels of a pandas frame: name, index type, monotonic (editable).
PandasMultiStringColumnFilterProxyModel cutepandas.pandasmodels.pandasindexfilterproxymodel Shows rows where every given column starts with its given prefix.
PandasStringColumnFilterProxyModel cutepandas.pandasmodels.pandasindexfilterproxymodel Filters a DataFrame by df.iloc[:, column].str.(search_term).
SchemaModel cutepandas.pandasmodels.schemamodel One row per column of a frame (any backend), read-only.
SortPermutation cutepandas.pandasmodels.dataframemodel A display-only sort order, see DataFrameModel.compute_sort_permutation.
VerticalHeaderModel cutepandas.pandasmodels.dataframemodel Row labels: one column per pandas index level; row numbers for other backends.

🛈 DocStrings

Pandas models.

CutePandas contains a range of tools to work with pandas data structures.

Models

DataFrameModel is a virtual table model for pandas, pyarrow and polars frames. It reads through a FrameSource (see cutepandas.frames) and converts only the visible window: rows are fetched in blocks per column, formatted once by per-dtype formatters and kept in a bounded, thread-safe LRU cache. pandas MultiIndex columns are shown by joining the levels with a separator (a Qt Property).

VerticalHeaderModel / HorizontalHeaderModel show one cell per index level; the DataFrameViewer widget combines them with the data table (synced on scrolling / resizing).

SchemaModel lists the columns of any frame (dtype, icon, null count, size), CategoryModel the categories of a categorical / enum column. Their pandas subclasses PandasColumnListModel and PandasCategoryListModel also edit the frame; PandasIndexListModel shows (and edits) the index levels.

Models can share one frame through a DataFrameHolder: a change made through one model (rename, dtype change, sorting, ...) shows up in all others.

Proxies

Since working with pandas often means working with tables containing several hundred thousands of rows, the default QSortFilterProxyModel does not work that well.

CutePandas includes several proxy models which try to improve this.

PandasStringColumnFilterProxyModel can be used to filter a column based on a search string. Instead of looping over the cells, a filter index is built using NumPy operations. This makes filtering super fast, even with several thousands of rows. A quick benchmark showed an almost 100x (!!) performance increase compared to QSortFilterProxyModel.

PandasEvalFilterProxyModel works in a similar way, but filtering is done by a DataFrame.eval expression (example: 'a > 10' shows all rows where the value of column "a" is greater than 10).

PandasMultiStringColumnFilterProxyModel shows the rows where several columns each start with a given prefix.

The proxies compute their masks with pandas: they need a pandas frame.

CategoryModel

Bases: TranslatableHeaderMixin, DataFrameHolderMixin, ModelMixin, AbstractTableModel

One row per category of a column, with its code and number of rows, read-only.

Works for pandas category and dictionary-encoded pd.ArrowDtype columns, polars Enum (fixed categories) and Categorical (the values present), and pyarrow dictionary columns. Other columns show no rows. Categories and counts are computed once per frame (one value_counts scan).

Source code in src/cutepandas/pandasmodels/categorymodel.py
class CategoryModel(
    TranslatableHeaderMixin,
    DataFrameHolderMixin,
    itemmodels.ModelMixin,
    core.AbstractTableModel,
):
    """One row per category of a column, with its code and number of rows, read-only.

    Works for pandas `category` and dictionary-encoded `pd.ArrowDtype` columns, polars
    `Enum` (fixed categories) and `Categorical` (the values present), and pyarrow
    dictionary columns. Other columns show no rows. Categories and counts are computed
    once per frame (one `value_counts` scan).
    """

    HEADER: ClassVar[list[str]] = [N_("Name"), N_("Code"), N_("Count")]

    def __init__(
        self,
        df: Any = None,
        col: Any = None,
        *,
        translate: Translate | None = None,
        **kwargs,
    ):
        """Show the categories of column `col` (a label).

        `translate` maps the English labels (header, tooltip) to the shown text.
        """
        super().__init__(**kwargs)
        self._translate = translate
        self.col = col
        self._categories: list[Any] | None = None
        self._counts: dict[Any, int] = {}
        self._init_holder(df)

    def _on_holder_changed(self, origin: Any):
        self._categories = None
        super()._on_holder_changed(origin)

    def column_position(self) -> int | None:
        source = self.source
        if source is None or self.col is None:
            return None
        for pos, info in enumerate(source.columns):
            if info.name == self.col:
                return pos
        return None

    @property
    def categories(self) -> list[Any]:
        if self._categories is None:
            pos = self.column_position()
            source = self.source
            if pos is None or source is None:
                self._categories, self._counts = [], {}
            else:
                self._categories = source.categories(pos) or []
                if self._categories:
                    self._counts = dict(source.value_counts(pos))
        return self._categories

    def count(self, category: Any) -> int:
        """Number of rows with this category."""
        _ = self.categories
        return self._counts.get(category, 0)

    def rowCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        return len(self.categories)

    def columnCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        return len(self.HEADER)

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        if not index.isValid() or index.row() >= len(self.categories):
            return None
        category = self.categories[index.row()]
        match role, index.column():
            case constants.DISPLAY_ROLE | constants.EDIT_ROLE, 0:
                return format_name(category)
            case constants.DISPLAY_ROLE | constants.EDIT_ROLE, 1:
                # A category's code is its position in the categories.
                return str(index.row())
            case constants.DISPLAY_ROLE, 2:
                return str(self.count(category))
            case constants.SORT_ROLE, 0:
                return format_name(category)
            case constants.SORT_ROLE, 1:
                return index.row()
            case constants.SORT_ROLE, 2:
                return self.count(category)
            case constants.ALIGNMENT_ROLE, 1 | 2:
                return constants.ALIGN_RIGHT | constants.ALIGN_V_CENTER
            case constants.DECORATION_ROLE, 0:
                return iconprovider.get_icon(iconnames.CATEGORY, as_qicon=True)
            case constants.NAME_ROLE | constants.USER_ROLE, _:
                return category
            case constants.TOOLTIP_ROLE, _:
                items = self._tr(N_("Items"))
                return f"<b>{category}</b><br>{items}: {self.count(category)}"
        return None

__init__

__init__(df: Any = None, col: Any = None, *, translate: Translate | None = None, **kwargs)

Show the categories of column col (a label).

translate maps the English labels (header, tooltip) to the shown text.

Source code in src/cutepandas/pandasmodels/categorymodel.py
def __init__(
    self,
    df: Any = None,
    col: Any = None,
    *,
    translate: Translate | None = None,
    **kwargs,
):
    """Show the categories of column `col` (a label).

    `translate` maps the English labels (header, tooltip) to the shown text.
    """
    super().__init__(**kwargs)
    self._translate = translate
    self.col = col
    self._categories: list[Any] | None = None
    self._counts: dict[Any, int] = {}
    self._init_holder(df)

count

count(category: Any) -> int

Number of rows with this category.

Source code in src/cutepandas/pandasmodels/categorymodel.py
def count(self, category: Any) -> int:
    """Number of rows with this category."""
    _ = self.categories
    return self._counts.get(category, 0)

CellChunk dataclass

One converted block of a column: everything data() returns, per row.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
@dataclass(slots=True)
class CellChunk:
    """One converted block of a column: everything `data()` returns, per row."""

    start: int
    values: list[Any]
    nulls: list[bool]
    display: list[str]
    scaled: bool = False
    """True once `normalized` / `colors` were computed (both stay None if the
    column is not numeric / boolean)."""
    normalized: list[float | None] | None = None
    colors: list[Any] | None = None

scaled class-attribute instance-attribute

scaled: bool = False

True once normalized / colors were computed (both stay None if the column is not numeric / boolean).

DataFrameHolder

Bases: Object

Holds the current frame for several models / widgets (GUI thread only).

Frame operations like rename or astype return a new frame instead of changing the old one. Models that share a holder always see the current frame: replacing it emits about_to_change and changed, and every model except the one that made the change (the origin) resets itself.

Accepts a pandas DataFrame / Series (a Series is stored as a one-column frame), a pyarrow Table, a polars DataFrame or any FrameSource. df is the native frame, source the backend-agnostic adapter the table models read through.

row_order is an optional display order (row positions, see set_row_order): a sort that only changes what the views show, without copying the frame. Replacing the frame clears it.

Source code in src/cutepandas/pandasmodels/dataframeholder.py
class DataFrameHolder(core.Object):
    """Holds the current frame for several models / widgets (GUI thread only).

    Frame operations like `rename` or `astype` return a new frame instead of changing
    the old one. Models that share a holder always see the current frame: replacing it
    emits `about_to_change` and `changed`, and every model except the one that made the
    change (the `origin`) resets itself.

    Accepts a pandas DataFrame / Series (a Series is stored as a one-column frame), a
    pyarrow Table, a polars DataFrame or any `FrameSource`. `df` is the native frame,
    `source` the backend-agnostic adapter the table models read through.

    `row_order` is an optional display order (row positions, see `set_row_order`):
    a sort that only changes what the views show, without copying the frame.
    Replacing the frame clears it.
    """

    about_to_change = core.Signal(object)  # ty: ignore[missing-argument]
    changed = core.Signal(object)  # ty: ignore[missing-argument]
    row_order_about_to_change = core.Signal(object)  # ty: ignore[missing-argument]
    row_order_changed = core.Signal(object)  # ty: ignore[missing-argument]

    def __init__(self, df: Any = None, **kwargs):
        super().__init__(**kwargs)
        self._df: Any = None
        self._source: FrameSource | None = None
        self._row_order: np.ndarray | None = None
        self._store(df)

    def _store(self, df: Any):
        self._row_order = None
        if isinstance(df, pd.Series):
            df = df.to_frame()
        if df is None:
            self._df, self._source = None, None
        elif isinstance(df, FrameSource) and not isinstance(df, pd.DataFrame):
            self._df, self._source = df.native, df
        else:
            self._df, self._source = df, None  # adapter created on first use

    @property
    def df(self) -> Any:
        """The native frame (pandas DataFrame, pyarrow Table, polars DataFrame)."""
        return self._df

    @df.setter
    def df(self, df: Any):
        self.set_df(df)

    @property
    def source(self) -> FrameSource | None:
        if self._source is None and self._df is not None:
            self._source = as_source(self._df)
        return self._source

    def set_df(self, df: Any, origin: Any = None):
        """Replace the frame. `origin` is passed on with the signals."""
        self.about_to_change.emit(origin)
        self._store(df)
        self.changed.emit(origin)

    @property
    def row_order(self) -> np.ndarray | None:
        """Display order of the rows (row positions), None for the frame's order."""
        return self._row_order

    def set_row_order(self, order: Any, origin: Any = None):
        """Show the rows in another order without touching the frame.

        Args:
            order: One row position per row (a permutation, e.g. from
                `PermutableSource.argsort`), or None for the frame's own order.
                Stored as an integer array: 8 bytes per row.
            origin: Passed on with the signals.
        """
        if order is not None:
            order = np.asarray(order, dtype=np.intp)
            rows = 0 if self.source is None else self.source.row_count
            if order.ndim != 1 or len(order) != rows:
                msg = f"Row order needs {rows} positions, got shape {order.shape}"
                raise ValueError(msg)
            if rows and (order.min() < 0 or order.max() >= rows):
                msg = "Row order contains positions outside the frame"
                raise ValueError(msg)
        self.row_order_about_to_change.emit(origin)
        self._row_order = order
        self.row_order_changed.emit(origin)

df property writable

df: Any

The native frame (pandas DataFrame, pyarrow Table, polars DataFrame).

row_order property

row_order: ndarray | None

Display order of the rows (row positions), None for the frame's order.

set_df

set_df(df: Any, origin: Any = None)

Replace the frame. origin is passed on with the signals.

Source code in src/cutepandas/pandasmodels/dataframeholder.py
def set_df(self, df: Any, origin: Any = None):
    """Replace the frame. `origin` is passed on with the signals."""
    self.about_to_change.emit(origin)
    self._store(df)
    self.changed.emit(origin)

set_row_order

set_row_order(order: Any, origin: Any = None)

Show the rows in another order without touching the frame.

Parameters:

Name Type Description Default
order Any

One row position per row (a permutation, e.g. from PermutableSource.argsort), or None for the frame's own order. Stored as an integer array: 8 bytes per row.

required
origin Any

Passed on with the signals.

None
Source code in src/cutepandas/pandasmodels/dataframeholder.py
def set_row_order(self, order: Any, origin: Any = None):
    """Show the rows in another order without touching the frame.

    Args:
        order: One row position per row (a permutation, e.g. from
            `PermutableSource.argsort`), or None for the frame's own order.
            Stored as an integer array: 8 bytes per row.
        origin: Passed on with the signals.
    """
    if order is not None:
        order = np.asarray(order, dtype=np.intp)
        rows = 0 if self.source is None else self.source.row_count
        if order.ndim != 1 or len(order) != rows:
            msg = f"Row order needs {rows} positions, got shape {order.shape}"
            raise ValueError(msg)
        if rows and (order.min() < 0 or order.max() >= rows):
            msg = "Row order contains positions outside the frame"
            raise ValueError(msg)
    self.row_order_about_to_change.emit(origin)
    self._row_order = order
    self.row_order_changed.emit(origin)

DataFrameModel

Bases: DataFrameHolderMixin, AbstractTableModel

Virtual table model for pandas, pyarrow and polars frames.

The model reads through a FrameSource and converts only what the view asks for: rows are fetched in blocks of chunk_rows per column, formatted once (per-dtype formatters, see FormatOptions) and kept in a bounded LRU ChunkCache. A 10M-row frame therefore costs the frame itself plus at most max_chunks converted blocks.

With color_values=True, numeric cells get a background whose intensity follows the value within the column's (min, max); booleans are green / red. The colours are computed per block (vectorised), not per data() call.

Sorting (sort, e.g. from a header click) has two modes:

  • "copy" (default): the source builds a sorted copy of the frame (SortableSource.sort), which replaces the holder's frame. The copy is as large as the frame and the old frame stays alive as long as someone references it.
  • "permutation": display-only. The source returns the sort order as row positions (PermutableSource.argsort, 8 bytes per row), stored as the holder's row_order; the frame is not copied or changed, and every visible block is read through the order (PermutableSource.fetch_rows). Row i of the model is row source_row(i) of the frame. Replacing the frame or clear_sort() drops the order.

Threads: all Qt methods (data, setData, sort, assigning df, setters) run on the GUI thread. prefetch() may run on any thread; it only fills the cache.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
class DataFrameModel(DataFrameHolderMixin, core.AbstractTableModel):
    """Virtual table model for pandas, pyarrow and polars frames.

    The model reads through a `FrameSource` and converts only what the view asks for:
    rows are fetched in blocks of `chunk_rows` per column, formatted once (per-dtype
    formatters, see `FormatOptions`) and kept in a bounded LRU `ChunkCache`. A 10M-row
    frame therefore costs the frame itself plus at most `max_chunks` converted blocks.

    With `color_values=True`, numeric cells get a background whose intensity follows
    the value within the column's (min, max); booleans are green / red. The colours
    are computed per block (vectorised), not per `data()` call.

    Sorting (`sort`, e.g. from a header click) has two modes:

    - `"copy"` (default): the source builds a sorted copy of the frame
      (`SortableSource.sort`), which replaces the holder's frame. The copy is as large
      as the frame and the old frame stays alive as long as someone references it.
    - `"permutation"`: display-only. The source returns the sort order as row
      positions (`PermutableSource.argsort`, 8 bytes per row), stored as the holder's
      `row_order`; the frame is not copied or changed, and every visible block is
      read through the order (`PermutableSource.fetch_rows`). Row `i` of the model is
      row `source_row(i)` of the frame. Replacing the frame or `clear_sort()` drops
      the order.

    Threads: all Qt methods (`data`, `setData`, `sort`, assigning `df`, setters) run
    on the GUI thread. `prefetch()` may run on any thread; it only fills the cache.
    """

    SUPPORTS = pd.DataFrame

    class Roles(enum.IntEnum):
        """Role names."""

        DTypeRole = constants.USER_ROLE + 4555
        """Backend dtype object of the column."""
        ColumnNameRole = constants.USER_ROLE + 4556
        """Column label."""
        KindRole = constants.USER_ROLE + 4557
        """`Kind` of the column."""
        IsNullRole = constants.USER_ROLE + 4558
        """True if the cell is missing."""
        NormalizedRole = constants.USER_ROLE + 4559
        """Numeric cell value scaled to 0..1 within the column (None if not numeric)."""

    def __init__(
        self,
        df: Any = None,
        *args,
        chunk_rows: int = 256,
        max_chunks: int = 256,
        format_options: FormatOptions | None = None,
        color_values: bool = False,
        dtype_icons: bool = False,
        read_only: bool = False,
        sort_mode: SortMode = "copy",
        **kwargs,
    ):
        """Show a frame.

        Args:
            df: pandas DataFrame / Series, pyarrow Table, polars DataFrame, a
                `FrameSource` or a `DataFrameHolder` (to share the frame with
                other models).
            chunk_rows: Rows per cached block.
            max_chunks: Maximum number of cached blocks (all columns together).
            format_options: How values are formatted for display.
            color_values: Colour numeric / boolean cells by value.
            dtype_icons: Show a dtype icon in the column headers.
            read_only: Disable editing even if the backend supports it.
            sort_mode: `"copy"` (sorted copy of the frame) or `"permutation"`
                (display-only row order, no copy); see the class docstring.
            args: Passed on to the Qt base class.
            kwargs: Passed on to the Qt base class.
        """
        self._multiindex_separator = " | "
        self._options = format_options or FormatOptions()
        self._color_values = color_values
        self._dtype_icons = dtype_icons
        self._kind_icons = icons.KindIconCache()
        self._read_only = read_only
        self._sort_mode: SortMode = sort_mode
        self._data_generation = 0
        self._palette: list[Any] | None = None
        self._cache: ChunkCache[CellChunk] = ChunkCache(chunk_rows, max_chunks)
        self._chunk_rows = chunk_rows
        self._state = _make_state(None, self._options)
        super().__init__(*args, **kwargs)
        self._init_holder(df)
        self.holder.row_order_about_to_change.connect(self._on_row_order_about_to_change)
        self.holder.row_order_changed.connect(self._on_row_order_changed)
        self._refresh_state()

    @classmethod
    def supports(cls, instance) -> bool:
        return isinstance(instance, pd.DataFrame | pa.Table) or is_polars_frame(instance)

    # --- frame state ---

    def _refresh_state(self):
        self._cache.clear()
        self._state = _make_state(self.source, self._options, self.holder.row_order)

    def _on_holder_changed(self, origin: Any):
        # Also for changes made by this model (sort): the cache belongs to the old frame.
        self._data_generation += 1
        self._refresh_state()
        super()._on_holder_changed(origin)

    def _on_row_order_about_to_change(self, origin: Any):
        self.layoutAboutToBeChanged.emit()

    def _on_row_order_changed(self, origin: Any):
        self._refresh_state()  # blocks were read in the old order
        self.layoutChanged.emit()

    @property
    def cache(self) -> ChunkCache[CellChunk]:
        return self._cache

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

    # --- chunk building (thread-safe) ---

    def _column_range(self, state: _FrameState, col: int) -> tuple[float, float] | None:
        with state.lock:
            if col in state.ranges:
                return state.ranges[col]
        assert state.source is not None
        value_range = state.source.value_range(col)  # full scan, outside the lock
        with state.lock:
            state.ranges[col] = value_range
        return value_range

    def _get_palette(self) -> list[Any]:
        if self._palette is None:
            color = gui.QColor("#e4572e")
            self._palette = [
                gui.QColor(
                    color.red(),
                    color.green(),
                    color.blue(),
                    int(i * 200 / (_PALETTE_STEPS - 1)),
                )
                for i in range(_PALETTE_STEPS)
            ]
        return self._palette

    def _add_colors(self, state: _FrameState, col: int, chunk: CellChunk):
        chunk.scaled = True
        kind = state.columns[col].kind
        if kind == Kind.BOOLEAN:
            true, false = gui.QColor(0, 160, 0, 50), gui.QColor(220, 0, 0, 50)
            chunk.normalized = [None if v is None else float(v) for v in chunk.values]
            chunk.colors = [
                None if v is None else (true if v else false) for v in chunk.values
            ]
            return
        if kind not in {Kind.INTEGER, Kind.FLOAT, Kind.DECIMAL}:
            return
        value_range = self._column_range(state, col)
        if value_range is None:
            return
        lo, hi = value_range
        try:
            values = np.array(chunk.values, dtype=float)
        except TypeError, ValueError:  # complex numbers
            return
        span = hi - lo
        scaled = (values - lo) / span if span else np.zeros_like(values)
        valid = np.isfinite(scaled)
        scaled = np.where(valid, np.clip(scaled, 0.0, 1.0), 0.0)
        steps = (scaled * (_PALETTE_STEPS - 1)).astype(np.intp)
        palette = self._get_palette()
        chunk.normalized = [
            s if ok else None for s, ok in zip(scaled.tolist(), valid.tolist())
        ]
        chunk.colors = [
            palette[s] if ok else None for s, ok in zip(steps.tolist(), valid.tolist())
        ]

    def _build_chunk(self, block: int, col: int) -> CellChunk:
        state = self._state
        assert state.source is not None
        start = block * self._chunk_rows
        stop = min(start + self._chunk_rows, state.row_count)
        if state.row_order is None:
            [fetched] = state.source.fetch(start, stop, [col])
        else:
            assert isinstance(state.source, PermutableSource)
            [fetched] = state.source.fetch_rows(state.row_order[start:stop], [col])
        display = format_chunk(
            fetched.values, fetched.nulls, state.formatters[col], self._options.null_text
        )
        chunk = CellChunk(start, fetched.values, fetched.nulls.tolist(), display)
        if self._color_values:
            self._add_colors(state, col, chunk)
        return chunk

    def _chunk(self, row: int, col: int) -> CellChunk:
        block = row // self._chunk_rows
        chunk = self._cache.get(block, col)
        if chunk is None:
            chunk = self._cache.get_or_build(block, col, self._build_chunk)
        return chunk

    def _scaled_chunk(self, row: int, col: int) -> CellChunk:
        chunk = self._chunk(row, col)
        if not chunk.scaled:  # on demand, once per block (GUI thread)
            self._add_colors(self._state, col, chunk)
        return chunk

    def source_row(self, row: int) -> int:
        """Row position in the frame of the model's row `row` (differs once sorted)."""
        order = self._state.row_order
        return row if order is None else int(order[row])

    def fetch_window(
        self, start: int, stop: int, columns: Sequence[int]
    ) -> list[ColumnChunk]:
        """Model rows `start:stop` of the given columns, in display order."""
        state = self._state
        if state.source is None:
            return []
        if state.row_order is None:
            return state.source.fetch(start, stop, columns)
        assert isinstance(state.source, PermutableSource)
        return state.source.fetch_rows(state.row_order[start:stop], columns)

    def prefetch(
        self, first_row: int, last_row: int, columns: Sequence[int] | None = None
    ):
        """Convert the blocks covering rows `first_row..last_row` (any thread)."""
        state = self._state
        if state.source is None or state.row_count == 0:
            return
        last_row = min(last_row, state.row_count - 1)
        cols = range(len(state.columns)) if columns is None else columns
        for block in range(
            first_row // self._chunk_rows, last_row // self._chunk_rows + 1
        ):
            for col in cols:
                self._cache.get_or_build(block, col, self._build_chunk)

    # --- Qt model API ---

    def rowCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        return self._state.row_count

    def columnCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        return len(self._state.columns)

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        if not index.isValid() or self._state.source is None:
            return None
        row, col = index.row(), index.column()
        match role:
            case constants.DISPLAY_ROLE:
                chunk = self._chunk(row, col)
                return chunk.display[row - chunk.start]
            case constants.ALIGNMENT_ROLE:
                return self._state.alignments[col]
            case constants.BACKGROUND_ROLE if self._color_values:
                chunk = self._scaled_chunk(row, col)
                return None if chunk.colors is None else chunk.colors[row - chunk.start]
            case constants.EDIT_ROLE | constants.USER_ROLE:
                chunk = self._chunk(row, col)
                return chunk.values[row - chunk.start]
            case constants.TOOLTIP_ROLE:
                chunk = self._chunk(row, col)
                offset = row - chunk.start
                return "null" if chunk.nulls[offset] else str(chunk.values[offset])
            case self.Roles.IsNullRole:
                chunk = self._chunk(row, col)
                return chunk.nulls[row - chunk.start]
            case self.Roles.NormalizedRole:
                chunk = self._scaled_chunk(row, col)
                if chunk.normalized is None:
                    return None
                return chunk.normalized[row - chunk.start]
            case self.Roles.DTypeRole:
                return self._state.columns[col].native_dtype
            case self.Roles.KindRole:
                return self._state.columns[col].kind
            case self.Roles.ColumnNameRole:
                return self._state.columns[col].name
        return None

    def headerData(
        self,
        section: int,
        orientation: constants.Orientation,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        columns = self._state.columns
        if orientation == constants.VERTICAL:
            if not 0 <= section < self._state.row_count:
                return None
            if role in {constants.DISPLAY_ROLE, constants.TOOLTIP_ROLE}:
                row = self.source_row(section)
                if isinstance(self.df, pd.DataFrame):
                    return format_name(self.df.index[row], self._multiindex_separator)
                return str(row)
            if role == constants.ALIGNMENT_ROLE:
                return constants.ALIGN_RIGHT | constants.ALIGN_V_CENTER
            return None
        if not 0 <= section < len(columns):
            return None
        info = columns[section]
        match role:
            case constants.DISPLAY_ROLE:
                return format_name(info.name, self._multiindex_separator)
            case constants.TOOLTIP_ROLE:
                label = format_name(info.name, self._multiindex_separator)
                return f"{label}\n{info.dtype}"
            case constants.ALIGNMENT_ROLE:
                return constants.ALIGN_CENTER
            case constants.DECORATION_ROLE if self._dtype_icons:
                return self._kind_icons.icon(info.kind)
            case self.Roles.DTypeRole:
                return info.native_dtype
            case self.Roles.KindRole:
                return info.kind
            case self.Roles.ColumnNameRole:
                return info.name
        return None

    def flags(self, index: core.ModelIndex) -> constants.ItemFlag:
        if not index.isValid():
            return constants.NO_FLAGS
        return _EDITABLE_FLAGS if self.is_editable() else _READ_ONLY_FLAGS

    def is_editable(self) -> bool:
        return not self._read_only and isinstance(self._state.source, EditableSource)

    def setData(
        self,
        index: core.ModelIndex,
        value: Any,
        role: constants.ItemDataRole = constants.EDIT_ROLE,
    ) -> bool:
        source = self._state.source
        if not index.isValid() or not self.is_editable():
            return False
        if role not in {constants.EDIT_ROLE, constants.USER_ROLE}:
            return False
        assert isinstance(source, EditableSource)
        row, col = index.row(), index.column()
        try:
            # In place: every model sharing the holder sees the same object.
            source.set_value(self.source_row(row), col, value)
        except Exception:
            logger.exception("Could not set %r at %s", value, (row, col))
            return False
        self._data_generation += 1  # a sort order computed before is stale now
        state = self._state
        with state.lock:
            state.ranges.pop(col, None)
        self._cache.invalidate(column=col)
        if self._color_values:  # the column range may have changed
            last = self.index(state.row_count - 1, col)
            self.dataChanged.emit(self.index(0, col), last)
        else:
            self.dataChanged.emit(index, index)
        return True

    def sort(self, ncol: int, order: constants.SortOrder = constants.ASCENDING):
        """Sort by column `ncol` (see `sort_mode`); unsupported sources are ignored."""
        source = self._state.source
        if not 0 <= ncol < self.columnCount():
            return
        descending = order == constants.DESCENDING
        if self._sort_mode == "permutation":
            if (permutation := self.compute_sort_permutation(ncol, order)) is not None:
                self.apply_sort_permutation(permutation)
            return
        if not isinstance(source, SortableSource):
            return
        new = source.sort(ncol, descending=descending)
        with self.change_layout():
            self.df = new

    def compute_sort_permutation(
        self, column: int, order: constants.SortOrder = constants.ASCENDING
    ) -> SortPermutation | None:
        """Compute a display-only sort order (any thread, e.g. a worker).

        Reads the frame through `PermutableSource.argsort` (stable, nulls last);
        the result is one integer per row. Returns None if the source can't sort.
        Apply it with `apply_sort_permutation` on the GUI thread.
        """
        generation = self._data_generation  # before reading: edits make it stale
        source = self._state.source
        if not isinstance(source, PermutableSource):
            return None
        descending = order == constants.DESCENDING
        positions = source.argsort(column, descending=descending)
        return SortPermutation(column, descending, positions, generation)

    def apply_sort_permutation(self, permutation: SortPermutation) -> bool:
        """Show the rows in a computed order (GUI thread).

        Returns False (and changes nothing) if the frame was replaced or edited
        since the order was computed.
        """
        if permutation.generation != self._data_generation:
            return False
        self.holder.set_row_order(permutation.positions, origin=self)
        return True

    def can_sort(self) -> bool:
        """True if the source supports sorting in the current `sort_mode`."""
        protocol = (
            PermutableSource if self._sort_mode == "permutation" else SortableSource
        )
        return isinstance(self._state.source, protocol)

    def clear_sort(self):
        """Back to the frame's own row order (drops a display-only sort)."""
        if self.holder.row_order is not None:
            self.holder.set_row_order(None, origin=self)

    @property
    def row_order(self) -> np.ndarray | None:
        """Display order of the rows (row positions), None if not permuted."""
        return self._state.row_order

    # --- options ---

    def _emit_all_changed(self):
        rows, cols = self.rowCount(), self.columnCount()
        if rows and cols:
            self.dataChanged.emit(self.index(0, 0), self.index(rows - 1, cols - 1))

    def set_format_options(self, options: FormatOptions):
        self._options = options
        self._refresh_state()
        self._emit_all_changed()

    def get_format_options(self) -> FormatOptions:
        return self._options

    def set_color_values(self, value: bool):
        self._color_values = value
        self._cache.clear()
        self._emit_all_changed()

    def get_color_values(self) -> bool:
        return self._color_values

    def set_dtype_icons(self, value: bool):
        self._dtype_icons = value
        if self.columnCount():
            self.headerDataChanged.emit(constants.HORIZONTAL, 0, self.columnCount() - 1)

    def get_dtype_icons(self) -> bool:
        return self._dtype_icons

    def set_sort_mode(self, mode: SortMode):
        if mode not in {"copy", "permutation"}:
            msg = f"Invalid sort mode {mode!r}"
            raise ValueError(msg)
        self._sort_mode = mode

    def get_sort_mode(self) -> SortMode:
        return self._sort_mode

    def set_read_only(self, value: bool):
        self._read_only = value

    def is_read_only(self) -> bool:
        return self._read_only

    def set_multiindex_separator(self, separator: str):
        self._multiindex_separator = separator

    def get_multiindex_separator(self) -> str:
        return self._multiindex_separator

    multiindex_separator = core.Property(
        str,
        get_multiindex_separator,
        set_multiindex_separator,
        doc="Separator to use for MultiIndexes",
    )
    color_values = core.Property(
        bool,
        get_color_values,
        set_color_values,
        doc="Colour numeric / boolean cells by value",
    )

row_order property

row_order: ndarray | None

Display order of the rows (row positions), None if not permuted.

Roles

Bases: IntEnum

Role names.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
class Roles(enum.IntEnum):
    """Role names."""

    DTypeRole = constants.USER_ROLE + 4555
    """Backend dtype object of the column."""
    ColumnNameRole = constants.USER_ROLE + 4556
    """Column label."""
    KindRole = constants.USER_ROLE + 4557
    """`Kind` of the column."""
    IsNullRole = constants.USER_ROLE + 4558
    """True if the cell is missing."""
    NormalizedRole = constants.USER_ROLE + 4559
    """Numeric cell value scaled to 0..1 within the column (None if not numeric)."""

ColumnNameRole class-attribute instance-attribute

ColumnNameRole = constants.USER_ROLE + 4556

Column label.

DTypeRole class-attribute instance-attribute

DTypeRole = constants.USER_ROLE + 4555

Backend dtype object of the column.

IsNullRole class-attribute instance-attribute

IsNullRole = constants.USER_ROLE + 4558

True if the cell is missing.

KindRole class-attribute instance-attribute

KindRole = constants.USER_ROLE + 4557

Kind of the column.

NormalizedRole class-attribute instance-attribute

NormalizedRole = constants.USER_ROLE + 4559

Numeric cell value scaled to 0..1 within the column (None if not numeric).

__init__

__init__(
    df: Any = None,
    *args,
    chunk_rows: int = 256,
    max_chunks: int = 256,
    format_options: FormatOptions | None = None,
    color_values: bool = False,
    dtype_icons: bool = False,
    read_only: bool = False,
    sort_mode: SortMode = "copy",
    **kwargs,
)

Show a frame.

Parameters:

Name Type Description Default
df Any

pandas DataFrame / Series, pyarrow Table, polars DataFrame, a FrameSource or a DataFrameHolder (to share the frame with other models).

None
chunk_rows int

Rows per cached block.

256
max_chunks int

Maximum number of cached blocks (all columns together).

256
format_options FormatOptions | None

How values are formatted for display.

None
color_values bool

Colour numeric / boolean cells by value.

False
dtype_icons bool

Show a dtype icon in the column headers.

False
read_only bool

Disable editing even if the backend supports it.

False
sort_mode SortMode

"copy" (sorted copy of the frame) or "permutation" (display-only row order, no copy); see the class docstring.

'copy'
args

Passed on to the Qt base class.

()
kwargs

Passed on to the Qt base class.

{}
Source code in src/cutepandas/pandasmodels/dataframemodel.py
def __init__(
    self,
    df: Any = None,
    *args,
    chunk_rows: int = 256,
    max_chunks: int = 256,
    format_options: FormatOptions | None = None,
    color_values: bool = False,
    dtype_icons: bool = False,
    read_only: bool = False,
    sort_mode: SortMode = "copy",
    **kwargs,
):
    """Show a frame.

    Args:
        df: pandas DataFrame / Series, pyarrow Table, polars DataFrame, a
            `FrameSource` or a `DataFrameHolder` (to share the frame with
            other models).
        chunk_rows: Rows per cached block.
        max_chunks: Maximum number of cached blocks (all columns together).
        format_options: How values are formatted for display.
        color_values: Colour numeric / boolean cells by value.
        dtype_icons: Show a dtype icon in the column headers.
        read_only: Disable editing even if the backend supports it.
        sort_mode: `"copy"` (sorted copy of the frame) or `"permutation"`
            (display-only row order, no copy); see the class docstring.
        args: Passed on to the Qt base class.
        kwargs: Passed on to the Qt base class.
    """
    self._multiindex_separator = " | "
    self._options = format_options or FormatOptions()
    self._color_values = color_values
    self._dtype_icons = dtype_icons
    self._kind_icons = icons.KindIconCache()
    self._read_only = read_only
    self._sort_mode: SortMode = sort_mode
    self._data_generation = 0
    self._palette: list[Any] | None = None
    self._cache: ChunkCache[CellChunk] = ChunkCache(chunk_rows, max_chunks)
    self._chunk_rows = chunk_rows
    self._state = _make_state(None, self._options)
    super().__init__(*args, **kwargs)
    self._init_holder(df)
    self.holder.row_order_about_to_change.connect(self._on_row_order_about_to_change)
    self.holder.row_order_changed.connect(self._on_row_order_changed)
    self._refresh_state()

apply_sort_permutation

apply_sort_permutation(permutation: SortPermutation) -> bool

Show the rows in a computed order (GUI thread).

Returns False (and changes nothing) if the frame was replaced or edited since the order was computed.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def apply_sort_permutation(self, permutation: SortPermutation) -> bool:
    """Show the rows in a computed order (GUI thread).

    Returns False (and changes nothing) if the frame was replaced or edited
    since the order was computed.
    """
    if permutation.generation != self._data_generation:
        return False
    self.holder.set_row_order(permutation.positions, origin=self)
    return True

can_sort

can_sort() -> bool

True if the source supports sorting in the current sort_mode.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def can_sort(self) -> bool:
    """True if the source supports sorting in the current `sort_mode`."""
    protocol = (
        PermutableSource if self._sort_mode == "permutation" else SortableSource
    )
    return isinstance(self._state.source, protocol)

clear_sort

clear_sort()

Back to the frame's own row order (drops a display-only sort).

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def clear_sort(self):
    """Back to the frame's own row order (drops a display-only sort)."""
    if self.holder.row_order is not None:
        self.holder.set_row_order(None, origin=self)

compute_sort_permutation

compute_sort_permutation(column: int, order: SortOrder = ASCENDING) -> SortPermutation | None

Compute a display-only sort order (any thread, e.g. a worker).

Reads the frame through PermutableSource.argsort (stable, nulls last); the result is one integer per row. Returns None if the source can't sort. Apply it with apply_sort_permutation on the GUI thread.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def compute_sort_permutation(
    self, column: int, order: constants.SortOrder = constants.ASCENDING
) -> SortPermutation | None:
    """Compute a display-only sort order (any thread, e.g. a worker).

    Reads the frame through `PermutableSource.argsort` (stable, nulls last);
    the result is one integer per row. Returns None if the source can't sort.
    Apply it with `apply_sort_permutation` on the GUI thread.
    """
    generation = self._data_generation  # before reading: edits make it stale
    source = self._state.source
    if not isinstance(source, PermutableSource):
        return None
    descending = order == constants.DESCENDING
    positions = source.argsort(column, descending=descending)
    return SortPermutation(column, descending, positions, generation)

fetch_window

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

Model rows start:stop of the given columns, in display order.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def fetch_window(
    self, start: int, stop: int, columns: Sequence[int]
) -> list[ColumnChunk]:
    """Model rows `start:stop` of the given columns, in display order."""
    state = self._state
    if state.source is None:
        return []
    if state.row_order is None:
        return state.source.fetch(start, stop, columns)
    assert isinstance(state.source, PermutableSource)
    return state.source.fetch_rows(state.row_order[start:stop], columns)

prefetch

prefetch(first_row: int, last_row: int, columns: Sequence[int] | None = None)

Convert the blocks covering rows first_row..last_row (any thread).

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def prefetch(
    self, first_row: int, last_row: int, columns: Sequence[int] | None = None
):
    """Convert the blocks covering rows `first_row..last_row` (any thread)."""
    state = self._state
    if state.source is None or state.row_count == 0:
        return
    last_row = min(last_row, state.row_count - 1)
    cols = range(len(state.columns)) if columns is None else columns
    for block in range(
        first_row // self._chunk_rows, last_row // self._chunk_rows + 1
    ):
        for col in cols:
            self._cache.get_or_build(block, col, self._build_chunk)

sort

sort(ncol: int, order: SortOrder = ASCENDING)

Sort by column ncol (see sort_mode); unsupported sources are ignored.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def sort(self, ncol: int, order: constants.SortOrder = constants.ASCENDING):
    """Sort by column `ncol` (see `sort_mode`); unsupported sources are ignored."""
    source = self._state.source
    if not 0 <= ncol < self.columnCount():
        return
    descending = order == constants.DESCENDING
    if self._sort_mode == "permutation":
        if (permutation := self.compute_sort_permutation(ncol, order)) is not None:
            self.apply_sort_permutation(permutation)
        return
    if not isinstance(source, SortableSource):
        return
    new = source.sort(ncol, descending=descending)
    with self.change_layout():
        self.df = new

source_row

source_row(row: int) -> int

Row position in the frame of the model's row row (differs once sorted).

Source code in src/cutepandas/pandasmodels/dataframemodel.py
def source_row(self, row: int) -> int:
    """Row position in the frame of the model's row `row` (differs once sorted)."""
    order = self._state.row_order
    return row if order is None else int(order[row])

HorizontalHeaderModel

Bases: DataFrameHolderMixin, AbstractTableModel

Column labels: one row per pandas column level; one row for other backends.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
class HorizontalHeaderModel(DataFrameHolderMixin, core.AbstractTableModel):
    """Column labels: one row per pandas column level; one row for other backends."""

    def __init__(self, df: Any = None, **kwargs):
        super().__init__(**kwargs)
        self._init_holder(df)

    def _pd_columns(self) -> pd.Index | None:
        df = self.df
        return df.columns if isinstance(df, pd.DataFrame) else None

    def columnCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        source = self.source
        return 0 if source is None else len(source.columns)

    def rowCount(self, parent: core.ModelIndex | None = None) -> int:
        if self.df is None or (parent is not None and parent.isValid()):
            return 0
        pd_columns = self._pd_columns()
        return 1 if pd_columns is None else pd_columns.nlevels

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        source = self.source
        if source is None or not index.isValid():
            return None
        match role:
            case constants.DISPLAY_ROLE | constants.TOOLTIP_ROLE:
                value = source.columns[index.column()].name
                if isinstance(self._pd_columns(), pd.MultiIndex):
                    value = value[index.row()]
                return str(value)
            case constants.ALIGNMENT_ROLE:
                return constants.ALIGN_CENTER
        return None

    def headerData(
        self,
        section: int,
        orientation: constants.Orientation,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        match role, orientation:
            case constants.DISPLAY_ROLE | constants.TOOLTIP_ROLE, constants.VERTICAL:
                pd_columns = self._pd_columns()
                if pd_columns is None:
                    return "" if section == 0 and self.df is not None else None
                if not 0 <= section < pd_columns.nlevels:
                    return None
                name = pd_columns.names[section]
                return "" if name is None else str(name)
        return None

PandasCategoryListModel

Bases: CategoryModel

CategoryModel for a pandas category column that also edits it.

Rename, reorder (drag and drop, sorting), add categories, toggle ordered, remove unused ones. USER_ROLE returns the rows of a category.

Source code in src/cutepandas/pandasmodels/pandascategorylistmodel.py
class PandasCategoryListModel(CategoryModel):
    """`CategoryModel` for a pandas `category` column that also edits it.

    Rename, reorder (drag and drop, sorting), add categories, toggle `ordered`,
    remove unused ones. `USER_ROLE` returns the rows of a category.
    """

    MIME_TYPE = "mime_categories"

    def __init__(
        self,
        df: pd.DataFrame | DataFrameHolder | None = None,
        col=None,
        parent=None,
        **kwargs,
    ):
        super().__init__(df, col, parent=parent, **kwargs)

    @property
    def series(self):
        assert self.df is not None
        return self.df[self.col]

    @series.setter
    def series(self, series):
        assert self.df is not None
        # A new frame (instead of df[col] = ...) so shared models get notified.
        # With copy-on-write the shallow copy doesn't touch the caller's frame.
        df = self.df.copy(deep=False)
        df[self.col] = series
        self.df = df

    def setData(
        self,
        index: core.ModelIndex,
        value: Any,
        role: constants.ItemDataRole = constants.EDIT_ROLE,
    ) -> bool:
        if not index.isValid():
            return False
        if role == constants.EDIT_ROLE and index.column() == 0:
            if value in self.series.cat.categories:
                logger.error("Error: Category names must be unique.")
                return False
            rename_dct = {index.data(constants.NAME_ROLE): value}
            with self.change_layout():
                self.series = self.series.cat.rename_categories(rename_dct)
            return True
        return False

    def flags(self, index: core.ModelIndex) -> constants.ItemFlag:
        if not index.isValid():
            return constants.DROP_ENABLED
        return self.DEFAULT_FLAGS | constants.IS_EDITABLE

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        if role == constants.USER_ROLE and index.isValid():
            category = self.categories[index.row()]
            assert self.df is not None
            return self.df[self.series == category]
        return super().data(index, role)

    def mimeData(self, indexes):
        mime_data = core.MimeData()
        data = [i.row() for i in indexes if i.column() == 0]
        mime_data.set_json_data(self.MIME_TYPE, data)
        return mime_data

    def mimeTypes(self):
        return [self.MIME_TYPE]

    def dropMimeData(self, mime_data, action, row, column, parent_index):
        if parent_index.isValid():
            return False

        if mime_data.hasFormat(self.MIME_TYPE):
            indexes = mime_data.get_json_data(self.MIME_TYPE)
            cats = self.series.cat.categories.tolist()
            cats = helpers.move_in_list(cats, indexes, row)
            self.reorder_categories(cats)
            return False
        return None

    def sort(self, ncol, order):
        if ncol != 0:
            return
        is_descending = order == constants.DESCENDING
        new_order = sorted(self.series.cat.categories, reverse=is_descending)
        self.reorder_categories(new_order)

    def reorder_categories(self, order):
        with self.change_layout():
            self.series = self.series.cat.reorder_categories(new_categories=order)

    def add_category(self, new_categories):
        if not pd.api.types.is_list_like(new_categories):
            new_categories = [new_categories]
        with self.append_rows(len(new_categories)):
            self.series = self.series.cat.add_categories(new_categories=new_categories)

    def toggle_ordered(self):
        with self.change_layout():
            if self.series.cat.ordered:
                self.series = self.series.cat.set_unordered()
            else:
                self.series = self.series.cat.set_ordered()

    def remove_unused(self):
        with self.change_layout():
            self.series = self.series.cat.remove_unused()

PandasColumnListModel

Bases: SchemaModel

SchemaModel for pandas frames that also edits them.

Rename (column 0), change the dtype (column 1, see DTypeDelegate), remove, reorder by drag and drop or by sorting, append columns and move index levels into the columns (drop from PandasIndexListModel).

Source code in src/cutepandas/pandasmodels/pandascolumnlistmodel.py
class PandasColumnListModel(SchemaModel):
    """`SchemaModel` for pandas frames that also edits them.

    Rename (column 0), change the dtype (column 1, see `DTypeDelegate`), remove,
    reorder by drag and drop or by sorting, append columns and move index levels into
    the columns (drop from `PandasIndexListModel`).
    """

    MIME_TYPE = "mime_columns"
    content_type = "features"

    def mimeData(self, indexes):
        mime_data = core.MimeData()
        data = [i.row() for i in indexes if i.column() == 0]
        mime_data.set_json_data(self.MIME_TYPE, data)
        return mime_data

    def dropMimeData(self, mime_data, action, row, column, parent_index):
        df = self.df
        if parent_index.isValid() or df is None:
            # Since we only drop in between items, parent_index must be invalid
            return False
        if mime_data.hasFormat(self.MIME_TYPE):
            data = mime_data.get_json_data(self.MIME_TYPE)
            positions = helpers.move_in_list(list(range(len(df.columns))), data, row)
            with self.change_layout():
                self.df = df.iloc[:, positions]
            self.update_all()
            return False

        if mime_data.hasFormat("mime_indexes"):
            data = mime_data.get_json_data("mime_indexes")
            with self.reset_model():
                self.df = df.reset_index(level=data)
            self.update_all()
        return False

    def mimeTypes(self):
        return [self.MIME_TYPE]

    def setData(
        self,
        index: core.ModelIndex,
        value: Any,
        role: constants.ItemDataRole = constants.EDIT_ROLE,
    ) -> bool:
        if not index.isValid() or self.df is None:
            return False
        match role, index.column():
            case constants.EDIT_ROLE, 0:
                return self._rename_column(index.row(), value)
            case constants.EDIT_ROLE, 1:
                return self._set_dtype(index.row(), value)
            case constants.USER_ROLE, _:
                return self._replace_column(index.row(), value)
            case self.Roles.DTypeRole, _:
                return self._set_dtype(index.row(), value)
        return False

    def _replace_column(self, pos: int, values: Any) -> bool:
        df = self.df
        assert df is not None
        # Build the new frame first: assigning self.df notifies the other models.
        new = df.copy(deep=False)
        new.isetitem(pos, values)
        self.df = new
        self.update_all()
        return True

    def _set_dtype(self, pos: int, dtype: Any) -> bool:
        df = self.df
        assert df is not None
        try:
            column = df.iloc[:, pos].astype(dtype)
        except TypeError, ValueError:
            logger.exception("Could not convert column %r to %r", pos, dtype)
            return False
        return self._replace_column(pos, column)

    def flags(self, index: core.ModelIndex) -> constants.ItemFlag:
        if not index.isValid():
            return constants.DROP_ENABLED
        if index.column() in {0, 1}:
            return self.DEFAULT_FLAGS | constants.IS_EDITABLE
        return self.DEFAULT_FLAGS

    def removeRows(self, row, count, parent):
        if self.df is None or count <= 0 or row < 0 or row + count > self.rowCount():
            return False
        keep = [i for i in range(len(self.df.columns)) if not row <= i < row + count]
        with self.remove_rows(row, row + count - 1, parent):
            self.df = self.df.iloc[:, keep]
        return True

    def _rename_column(self, pos: int, name: Any) -> bool:
        df = self.df
        assert df is not None
        if isinstance(df.columns, pd.MultiIndex) or name in df.columns:
            return False  # a label can't replace a tuple; names stay unique
        labels = list(df.columns)
        labels[pos] = name
        self.df = df.set_axis(labels, axis="columns")
        self.update_all()
        return True

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        if index.isValid() and role == constants.USER_ROLE and self.df is not None:
            return self.data_by_index(index)
        return super().data(index, role)

    def sort(self, ncol: int, order: constants.SortOrder = constants.ASCENDING):
        if self.df is None:
            return
        if not 0 <= ncol < len(self.HEADER):
            return
        keys = [
            self.data(self.index(row, ncol), constants.SORT_ROLE)
            for row in range(self.rowCount())
        ]
        positions = sorted(
            range(len(keys)),
            key=keys.__getitem__,
            reverse=order == constants.DESCENDING,
        )
        with self.change_layout():
            # positional, so duplicate column labels survive the reorder
            self.df = self.df.iloc[:, positions]

    def data_by_index(self, index: core.ModelIndex):
        df = self.df
        assert df is not None
        return df.iloc[:, index.row()]

    def add_feature(self, series: pd.Series):
        """Append a Series as a new column (named after the Series)."""
        df = self.df
        assert df is not None
        new = df.copy(deep=False)
        with self.append_rows(1):
            new[series.name] = series
            self.df = new

add_feature

add_feature(series: Series)

Append a Series as a new column (named after the Series).

Source code in src/cutepandas/pandasmodels/pandascolumnlistmodel.py
def add_feature(self, series: pd.Series):
    """Append a Series as a new column (named after the Series)."""
    df = self.df
    assert df is not None
    new = df.copy(deep=False)
    with self.append_rows(1):
        new[series.name] = series
        self.df = new

PandasEvalFilterProxyModel

Bases: BasePandasIndexFilterProxyModel

Filters a DataFrame by a boolean DataFrame.eval expression, like 'a > 10'.

Invalid expressions, or ones that don't evaluate to a boolean Series, show no rows.

Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
class PandasEvalFilterProxyModel(BasePandasIndexFilterProxyModel):
    """Filters a DataFrame by a boolean `DataFrame.eval` expression, like 'a > 10'.

    Invalid expressions, or ones that don't evaluate to a boolean Series, show no rows.
    """

    ID = "pandas_eval_filter"

    def __init__(self, **kwargs):
        self._expression = ""
        super().__init__(**kwargs)

    def compute_filter(self, df: pd.DataFrame) -> np.ndarray | None:
        if not self._expression:
            return None
        try:
            result = df.eval(self._expression)
        except Exception:  # noqa: BLE001 (user input: any syntax / name / type error)
            logger.debug("Invalid filter expression %r", self._expression)
            return np.zeros(len(df), dtype=bool)
        if not pd.api.types.is_bool_dtype(getattr(result, "dtype", None)):
            return np.zeros(len(df), dtype=bool)
        return _to_mask(result, len(df))

    def set_expression(self, expression: str):
        self._expression = expression
        if self.sourceModel() is not None:
            self.invalidate_filter()

    def get_expression(self) -> str:
        return self._expression

    expression = core.Property(
        str,
        get_expression,
        set_expression,
        doc="Expression to use for filtering",
    )

PandasIndexListModel

Bases: TranslatableHeaderMixin, DataFrameHolderMixin, ModelMixin, AbstractTableModel

Index levels of a pandas frame: name, index type, monotonic (editable).

Labels go through translate (see cutepandas.utils.i18n).

Source code in src/cutepandas/pandasmodels/pandascolumnlistmodel.py
class PandasIndexListModel(
    TranslatableHeaderMixin,
    DataFrameHolderMixin,
    itemmodels.ModelMixin,
    core.AbstractTableModel,
):
    """Index levels of a pandas frame: name, index type, monotonic (editable).

    Labels go through `translate` (see `cutepandas.utils.i18n`).
    """

    HEADER: ClassVar[list[str]] = [N_("Name"), N_("Index type"), N_("Monotonic")]
    MIME_TYPE = "mime_indexes"

    def __init__(
        self,
        ds: pd.DataFrame | DataFrameHolder | None = None,
        *,
        translate: Translate | None = None,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self._translate = translate
        self._init_holder(ds)

    def setData(
        self,
        index: core.ModelIndex,
        value: Any,
        role: constants.ItemDataRole = constants.EDIT_ROLE,
    ) -> bool:
        if not index.isValid():
            return False
        assert self.df is not None
        match role:
            case constants.EDIT_ROLE if index.column() == 0:
                level = index.row() if isinstance(self.df.index, pd.MultiIndex) else None
                self._set_index(self.df.index.set_names(names=value, level=level))
                self.dataChanged.emit(index, index)
                return True
            case constants.USER_ROLE if not isinstance(self.df.index, pd.MultiIndex):
                with self.change_layout():
                    self._set_index(value)
                return True
            case self.DTYPE_ROLE:
                try:
                    new_index = self.df.index.astype(value)
                except TypeError, ValueError:
                    logger.exception("Could not convert index to %r", value)
                    return False
                with self.change_layout():
                    self._set_index(new_index)
                return True
        return False

    def removeRows(self, row, count, parent=None):
        """Remove index levels (the rows of this model) from the DataFrame."""
        if self.df is None or count <= 0 or row < 0 or row + count > self.rowCount():
            return False
        with self.remove_rows(row, row + count - 1, parent):
            # drop=True discards the level values instead of moving them into columns.
            # Removing every level leaves a fresh RangeIndex.
            self.df = self.df.reset_index(level=list(range(row, row + count)), drop=True)
        return True

    def flags(self, index: core.ModelIndex) -> constants.ItemFlag:
        if not index.isValid():
            return constants.DROP_ENABLED
        assert self.df is not None
        is_range = self.df.index.name is None and isinstance(self.df.index, pd.RangeIndex)
        match index.column(), is_range:
            case 0, True:
                # do not allow moving the "default" RangeIndex.
                return (
                    constants.IS_ENABLED | constants.IS_SELECTABLE | constants.IS_EDITABLE
                )
            case _, True:
                return constants.IS_ENABLED | constants.IS_SELECTABLE
            case 0 | 1, False:
                return self.DEFAULT_FLAGS | constants.IS_EDITABLE
            case _, False:
                return self.DEFAULT_FLAGS

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        if not index.isValid():
            return None
        assert self.df is not None
        match role, index.column():
            # case constants.DECORATION_ROLE, 0:
            #     index = self.get_index(index.row())
            #     return icons.icon_for_index(index)

            case constants.TOOLTIP_ROLE, _:
                index = self.get_index(index.row())
                return (
                    f"<b>{index.name}</b><br>{self._tr(N_('Contains NaNs'))}: "
                    f"{index.hasnans}<br>"
                    # f"{_('Monotonic')}: {index.is_monotonic}"
                )

            case constants.DISPLAY_ROLE | constants.EDIT_ROLE, 0:
                index_name = self.df.index.names[index.row()]
                return index_name or self._tr(N_("[Unnamed]"))

            case constants.DISPLAY_ROLE | constants.EDIT_ROLE, 1:
                return self._tr(label_for_index(self.get_index(index.row())))

            case constants.DISPLAY_ROLE | constants.EDIT_ROLE, 2:
                index = self.get_index(index.row())
                if index.is_monotonic_increasing:
                    return self._tr(N_("Increasing"))
                if index.is_monotonic_decreasing:
                    return self._tr(N_("Decreasing"))

            case constants.USER_ROLE, _:
                name = self.df.index.names[index.row()]
                return self.df.index.get_level_values(name)

            case constants.NAME_ROLE, _:
                return self.df.index.names[index.row()]

            case self.DTYPE_ROLE, _:
                return self.get_index(index.row()).dtype
        return None

    def rowCount(self, parent: core.ModelIndex | None = None) -> int:
        if self.df is None or (parent is not None and parent.isValid()):
            return 0
        return self.df.index.nlevels

    def columnCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        return len(self.HEADER)

    def mimeData(self, indexes):
        mime_data = core.MimeData()
        data = [i.row() for i in indexes if i.column() == 0]
        mime_data.set_json_data(self.MIME_TYPE, data)
        return mime_data

    def dropMimeData(self, mime_data, action, row, column, parent_index):
        if parent_index.isValid():
            return False
        assert self.df is not None
        if mime_data.hasFormat(self.MIME_TYPE):
            data = mime_data.get_json_data(self.MIME_TYPE)
            names = list(self.df.index.names)
            names = helpers.move_in_list(names, data, row)
            with self.change_layout():
                self.df = self.df.reorder_levels(order=names)
        elif mime_data.hasFormat("mime_columns"):
            data = mime_data.get_json_data("mime_columns")
            cols = self.df.columns.tolist()
            to_append = [cols[i] for i in data]
            # TODO: make sure drop offset is taken into account
            with self.reset_model():
                self.df = self.df.set_index(keys=to_append, append=True)
        return False

    def mimeTypes(self):
        return [self.MIME_TYPE]

    def get_index(self, row: int = 0):
        assert self.df is not None
        idx = self.df.index
        # using get_level_values() is too slow for large datasets with multiindex
        return idx.levels[row] if isinstance(idx, pd.MultiIndex) else idx

    def _set_index(self, new_index):
        # A new frame (instead of assigning df.index) so shared models get notified.
        assert self.df is not None
        self.df = self.df.set_axis(new_index, axis="index")

    def to_datetime(self, level: int | None = None, fmt: str | None = None):
        """Convert the index (or one level of a MultiIndex) to datetimes."""
        assert self.df is not None
        index = self.df.index
        if isinstance(index, pd.MultiIndex):
            level = level or 0
            converted = pd.to_datetime(index.levels[level], format=fmt)
            new_index = index.set_levels(converted, level=level)
        else:
            new_index = pd.to_datetime(index, format=fmt)
        with self.change_layout():
            self._set_index(new_index)

    def filter_range(self, start: int, end: int):
        assert self.df is not None
        with self.change_layout():
            self.df = self.df.iloc[start:end]
        return True

removeRows

removeRows(row, count, parent=None)

Remove index levels (the rows of this model) from the DataFrame.

Source code in src/cutepandas/pandasmodels/pandascolumnlistmodel.py
def removeRows(self, row, count, parent=None):
    """Remove index levels (the rows of this model) from the DataFrame."""
    if self.df is None or count <= 0 or row < 0 or row + count > self.rowCount():
        return False
    with self.remove_rows(row, row + count - 1, parent):
        # drop=True discards the level values instead of moving them into columns.
        # Removing every level leaves a fresh RangeIndex.
        self.df = self.df.reset_index(level=list(range(row, row + count)), drop=True)
    return True

to_datetime

to_datetime(level: int | None = None, fmt: str | None = None)

Convert the index (or one level of a MultiIndex) to datetimes.

Source code in src/cutepandas/pandasmodels/pandascolumnlistmodel.py
def to_datetime(self, level: int | None = None, fmt: str | None = None):
    """Convert the index (or one level of a MultiIndex) to datetimes."""
    assert self.df is not None
    index = self.df.index
    if isinstance(index, pd.MultiIndex):
        level = level or 0
        converted = pd.to_datetime(index.levels[level], format=fmt)
        new_index = index.set_levels(converted, level=level)
    else:
        new_index = pd.to_datetime(index, format=fmt)
    with self.change_layout():
        self._set_index(new_index)

PandasMultiStringColumnFilterProxyModel

Bases: BasePandasIndexFilterProxyModel

Shows rows where every given column starts with its given prefix.

Filters are a mapping of column label to prefix; empty prefixes are ignored.

Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
class PandasMultiStringColumnFilterProxyModel(BasePandasIndexFilterProxyModel):
    """Shows rows where every given column starts with its given prefix.

    Filters are a mapping of column label to prefix; empty prefixes are ignored.
    """

    def __init__(self, **kwargs):
        self._filters: dict[str, str] = {}
        super().__init__(**kwargs)

    def compute_filter(self, df: pd.DataFrame) -> np.ndarray | None:
        active = {k: v for k, v in self._filters.items() if v}
        if not active:
            return None
        mask = np.ones(len(df), dtype=bool)
        for column, prefix in active.items():
            if column not in df.columns:
                return np.zeros(len(df), dtype=bool)
            series = _as_string_series(df[column])
            mask &= _to_mask(series.str.startswith(prefix, na=False), len(df))
        return mask

    def set_filters(self, filters: dict[str, str]):
        self._filters = dict(filters)
        if self.sourceModel() is not None:
            self.invalidate_filter()

    def get_filters(self) -> dict[str, str]:
        return self._filters

    filters = core.Property(
        dict,
        get_filters,
        set_filters,
        doc="Dictionary containing a Column->Prefix mapping",
    )

PandasStringColumnFilterProxyModel

Bases: BasePandasIndexFilterProxyModel

Filters a DataFrame by df.iloc[:, column].str.(search_term).

Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
class PandasStringColumnFilterProxyModel(BasePandasIndexFilterProxyModel):
    """Filters a DataFrame by df.iloc[:, column].str.<filter_mode>(search_term)."""

    ID = "pandas_str_filter"

    def __init__(self, **kwargs):
        self._filter_column = 0
        self._filter_mode: FilterModeStr = "startswith"
        self._case_sensitive = True
        self._flags = 0
        self._search_term = ""
        self._na_value = False
        super().__init__(**kwargs)

    def compute_filter(self, df: pd.DataFrame) -> np.ndarray | None:
        if not self._search_term:
            return None
        if not 0 <= self._filter_column < len(df.columns):
            return np.zeros(len(df), dtype=bool)
        column = _as_string_series(df.iloc[:, self._filter_column])
        term = self._search_term
        match self._filter_mode:
            case "startswith" | "endswith" if not self._case_sensitive:
                method = getattr(column.str.lower().str, self._filter_mode)
                result = method(term.lower(), na=self._na_value)
            case "startswith" | "endswith":
                result = getattr(column.str, self._filter_mode)(term, na=self._na_value)
            case "contains" | "match":
                method = getattr(column.str, self._filter_mode)
                result = method(
                    term, case=self._case_sensitive, flags=self._flags, na=self._na_value
                )
        return _to_mask(result, len(df), self._na_value)

    def _refilter(self):
        if self.sourceModel() is not None:
            self.invalidate_filter()

    def set_search_term(self, search_term: str):
        self._search_term = search_term
        self._refilter()

    def get_search_term(self) -> str:
        return self._search_term

    def set_filter_column(self, column: int):
        self._filter_column = column
        self._refilter()

    def get_filter_column(self) -> int:
        return self._filter_column

    def set_filter_mode(self, mode: FilterModeStr):
        if mode not in FILTER_MODES:
            msg = f"Invalid filter mode {mode!r}. Valid: {FILTER_MODES}"
            raise ValueError(msg)
        self._filter_mode = mode
        self._refilter()

    def get_filter_mode(self) -> FilterModeStr:
        return self._filter_mode

    def set_case_sensitive(self, mode: bool):
        self._case_sensitive = mode
        self._refilter()

    def is_case_sensitive(self) -> bool:
        return self._case_sensitive

    def set_flags(self, flags: int):
        self._flags = flags
        self._refilter()

    def get_flags(self) -> int:
        return self._flags

    def set_na_value(self, value: bool):
        self._na_value = value
        self._refilter()

    def get_na_value(self) -> bool:
        return self._na_value

    search_term = core.Property(
        str,
        get_search_term,
        set_search_term,
        doc="Term to use for filtering",
    )
    filter_column = core.Property(
        int,
        get_filter_column,
        set_filter_column,
        doc="Column to use for filtering",
    )
    filter_mode = core.Property(
        str,
        get_filter_mode,
        set_filter_mode,
        doc="Filter mode",
    )
    case_sensitive = core.Property(
        bool,
        is_case_sensitive,
        set_case_sensitive,
        doc="Case sensitivity of the filter",
    )
    re_flags = core.Property(
        int,
        get_flags,
        set_flags,
        doc="Regex Flags for match and contains mode",
    )
    na_value = core.Property(
        bool,
        get_na_value,
        set_na_value,
        doc="Whether rows with missing values are shown",
    )

SchemaModel

Bases: TranslatableHeaderMixin, DataFrameHolderMixin, ModelMixin, AbstractTableModel

One row per column of a frame (any backend), read-only.

Null counts and sizes are computed on first display of a row and cached until the frame changes (a null count scans the column; polars and pyarrow keep it in metadata). Sort it with a SortFilterProxyModel on SORT_ROLE.

Labels (HEADER, tooltips) go through translate (see cutepandas.utils.i18n).

Source code in src/cutepandas/pandasmodels/schemamodel.py
class SchemaModel(
    TranslatableHeaderMixin,
    DataFrameHolderMixin,
    itemmodels.ModelMixin,
    core.AbstractTableModel,
):
    """One row per column of a frame (any backend), read-only.

    Null counts and sizes are computed on first display of a row and cached until the
    frame changes (a null count scans the column; polars and pyarrow keep it in
    metadata). Sort it with a `SortFilterProxyModel` on `SORT_ROLE`.

    Labels (`HEADER`, tooltips) go through `translate` (see `cutepandas.utils.i18n`).
    """

    HEADER: ClassVar[list[str]] = [N_("Name"), N_("Type"), N_("Nulls"), N_("Size")]

    class Roles(enum.IntEnum):
        """Role names."""

        DTypeRole = constants.USER_ROLE + 4555
        ColumnNameRole = constants.USER_ROLE + 4556
        KindRole = constants.USER_ROLE + 4557
        ColumnInfoRole = constants.USER_ROLE + 4560

    def __init__(self, df: Any = None, *, translate: Translate | None = None, **kwargs):
        super().__init__(**kwargs)
        self._translate = translate
        self._null_counts: dict[int, int] = {}
        self._sizes: dict[int, int] = {}
        self._kind_icons = icons.KindIconCache()
        self._init_holder(df)

    def _on_holder_changed(self, origin: Any):
        self._null_counts.clear()
        self._sizes.clear()
        super()._on_holder_changed(origin)

    def column(self, row: int) -> ColumnInfo:
        source = self.source
        assert source is not None
        return source.columns[row]

    def null_count(self, row: int) -> int:
        if (count := self._null_counts.get(row)) is None:
            assert self.source is not None
            count = self._null_counts[row] = self.source.null_count(row)
        return count

    def nbytes(self, row: int) -> int:
        if (size := self._sizes.get(row)) is None:
            assert self.source is not None
            size = self._sizes[row] = self.source.nbytes(row)
        return size

    def rowCount(self, parent: core.ModelIndex | None = None) -> int:
        source = self.source
        if source is None or (parent is not None and parent.isValid()):
            return 0
        return len(source.columns)

    def columnCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        return len(self.HEADER)

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        if not index.isValid() or self.source is None:
            return None
        row = index.row()
        info = self.column(row)
        match role, index.column():
            case constants.DISPLAY_ROLE | constants.EDIT_ROLE, 0:
                return info.label
            case constants.DISPLAY_ROLE | constants.EDIT_ROLE, 1:
                return info.dtype
            case constants.DISPLAY_ROLE, 2:
                return str(self.null_count(row))
            case constants.DISPLAY_ROLE, 3:
                return core.Locale().get_formatted_data_size(self.nbytes(row))
            case constants.SORT_ROLE, 0:
                return info.label
            case constants.SORT_ROLE, 1:
                return info.dtype
            case constants.SORT_ROLE, 2:
                return self.null_count(row)
            case constants.SORT_ROLE, 3:
                return self.nbytes(row)
            case constants.ALIGNMENT_ROLE, 2 | 3:
                return constants.ALIGN_RIGHT | constants.ALIGN_V_CENTER
            case constants.DECORATION_ROLE, 0:
                return self._kind_icons.icon(info.kind)
            case constants.TOOLTIP_ROLE, _:
                return (
                    f"<b>{info.label}</b><br>{self._tr(N_('Type'))}: {info.dtype}"
                    f" ({info.kind.value})<br>{self._tr(N_('Nulls'))}: "
                    f"{self.null_count(row)}"
                )
            case self.Roles.DTypeRole, _:
                return info.native_dtype
            case self.Roles.KindRole, _:
                return info.kind
            case self.Roles.ColumnNameRole | constants.NAME_ROLE, _:
                return info.name
            case self.Roles.ColumnInfoRole, _:
                return info
        return None

Roles

Bases: IntEnum

Role names.

Source code in src/cutepandas/pandasmodels/schemamodel.py
class Roles(enum.IntEnum):
    """Role names."""

    DTypeRole = constants.USER_ROLE + 4555
    ColumnNameRole = constants.USER_ROLE + 4556
    KindRole = constants.USER_ROLE + 4557
    ColumnInfoRole = constants.USER_ROLE + 4560

SortPermutation dataclass

A display-only sort order, see DataFrameModel.compute_sort_permutation.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
@dataclass(frozen=True, slots=True)
class SortPermutation:
    """A display-only sort order, see `DataFrameModel.compute_sort_permutation`."""

    column: int
    descending: bool
    positions: np.ndarray
    """Row positions of the frame in display order (8 bytes per row)."""
    generation: int
    """Data generation of the model it was computed for (stale check)."""

generation instance-attribute

generation: int

Data generation of the model it was computed for (stale check).

positions instance-attribute

positions: ndarray

Row positions of the frame in display order (8 bytes per row).

VerticalHeaderModel

Bases: DataFrameHolderMixin, AbstractTableModel

Row labels: one column per pandas index level; row numbers for other backends.

Source code in src/cutepandas/pandasmodels/dataframemodel.py
class VerticalHeaderModel(DataFrameHolderMixin, core.AbstractTableModel):
    """Row labels: one column per pandas index level; row numbers for other backends."""

    def __init__(self, df: Any = None, **kwargs):
        super().__init__(**kwargs)
        self._init_holder(df)
        # A display-only sort (holder.row_order) moves the row labels too.
        self.holder.row_order_about_to_change.connect(self._on_row_order_about_to_change)
        self.holder.row_order_changed.connect(self._on_row_order_changed)

    def _on_row_order_about_to_change(self, origin: Any):
        self.layoutAboutToBeChanged.emit()

    def _on_row_order_changed(self, origin: Any):
        self.layoutChanged.emit()

    def _row(self, row: int) -> int:
        order = self.holder.row_order
        return row if order is None else int(order[row])

    def _index(self) -> pd.Index | None:
        df = self.df
        return df.index if isinstance(df, pd.DataFrame) else None

    def columnCount(self, parent: core.ModelIndex | None = None) -> int:
        if self.df is None or (parent is not None and parent.isValid()):
            return 0
        index = self._index()
        return 1 if index is None else index.nlevels

    def rowCount(self, parent: core.ModelIndex | None = None) -> int:
        if parent is not None and parent.isValid():
            return 0
        source = self.source
        return 0 if source is None else source.row_count

    def data(
        self,
        index: core.ModelIndex,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        if self.df is None or not index.isValid():
            return None
        match role:
            case constants.DISPLAY_ROLE | constants.TOOLTIP_ROLE:
                pd_index = self._index()
                row = self._row(index.row())
                if pd_index is None:
                    return str(row)
                value = pd_index[row]
                if isinstance(pd_index, pd.MultiIndex):
                    value = value[index.column()]
                return str(value)
        return None

    def headerData(
        self,
        section: int,
        orientation: constants.Orientation,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ) -> str | None:
        match role, orientation:
            case constants.DISPLAY_ROLE | constants.TOOLTIP_ROLE, constants.HORIZONTAL:
                pd_index = self._index()
                if pd_index is None:
                    return "" if section == 0 and self.df is not None else None
                if not 0 <= section < pd_index.nlevels:
                    return None
                name = pd_index.names[section]
                return "" if name is None else str(name)
        return None