Skip to content

CategoryModel

Sub classes

Name Children Inherits
PandasCategoryListModel
cutepandas.pandasmodels.pandascategorylistmodel
`CategoryModel` for a pandas `category` column that also edits it.

    Base classes

    Name Children Inherits
    TranslatableHeaderMixin
    cutepandas.utils.i18n
    Item model mixin: horizontal header labels from `HEADER`, translated.
    DataFrameHolderMixin
    cutepandas.pandasmodels.dataframeholder
    Model mixin: keeps `self.df` in a (possibly shared) DataFrameHolder.
    ModelMixin
    prettyqt.itemmodels.modelmixin
    AbstractTableModel
    prettyqt.core.abstracttablemodel
    Abstract model that can be subclassed to create table models.

    ⋔ Inheritance diagram

    graph TD
      2298428083["categorymodel.CategoryModel"]
      1559661765["i18n.TranslatableHeaderMixin"]
      3771062457["i18n.TranslateMixin"]
      2751680898["builtins.object"]
      103874424["dataframeholder.DataFrameHolderMixin"]
      3514613245["itemmodels.ModelMixin"]
      656210031["core.AbstractTableModel"]
      4092674192["core.AbstractTableModelMixin"]
      3882849576["core.AbstractItemModelMixin"]
      3227531497["core.ObjectMixin"]
      1115338939["QtCore.QAbstractTableModel"]
      930985301["QtCore.QAbstractItemModel"]
      13951691["QtCore.QObject"]
      395147830["sip.wrapper"]
      46922758["sip.simplewrapper"]
      1559661765 --> 2298428083
      3771062457 --> 1559661765
      2751680898 --> 3771062457
      103874424 --> 2298428083
      2751680898 --> 103874424
      3514613245 --> 2298428083
      2751680898 --> 3514613245
      656210031 --> 2298428083
      4092674192 --> 656210031
      3882849576 --> 4092674192
      3227531497 --> 3882849576
      2751680898 --> 3227531497
      1115338939 --> 656210031
      930985301 --> 1115338939
      13951691 --> 930985301
      395147830 --> 13951691
      46922758 --> 395147830
      2751680898 --> 46922758

    🛈 DocStrings

    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)
    

    :fa-brands-github: Show source on GitHub