Skip to content

BasePandasIndexFilterProxyModel

Sub classes

Name Children Inherits
PandasStringColumnFilterProxyModel
cutepandas.pandasmodels.pandasindexfilterproxymodel
Filters a DataFrame by df.iloc[:, column].str.<filter_mode>(search_term).
    PandasEvalFilterProxyModel
    cutepandas.pandasmodels.pandasindexfilterproxymodel
    Filters a DataFrame by a boolean `DataFrame.eval` expression, like 'a > 10'.
      PandasMultiStringColumnFilterProxyModel
      cutepandas.pandasmodels.pandasindexfilterproxymodel
      Shows rows where every given column starts with its given prefix.

        Base classes

        Name Children Inherits
        AbstractProxyModel
        prettyqt.core.abstractproxymodel
        Base class for proxy item models that can do sorting, filtering and processing.

        ⋔ Inheritance diagram

        graph TD
          1453093054["pandasindexfilterproxymodel.BasePandasIndexFilterProxyModel"]
          1274898529["core.AbstractProxyModel"]
          2431222121["core.AbstractProxyModelMixin"]
          3882849576["core.AbstractItemModelMixin"]
          3227531497["core.ObjectMixin"]
          2751680898["builtins.object"]
          2723940761["QtCore.QAbstractProxyModel"]
          930985301["QtCore.QAbstractItemModel"]
          13951691["QtCore.QObject"]
          395147830["sip.wrapper"]
          46922758["sip.simplewrapper"]
          1274898529 --> 1453093054
          2431222121 --> 1274898529
          3882849576 --> 2431222121
          3227531497 --> 3882849576
          2751680898 --> 3227531497
          2723940761 --> 1274898529
          930985301 --> 2723940761
          13951691 --> 930985301
          395147830 --> 13951691
          46922758 --> 395147830
          2751680898 --> 46922758

        🛈 DocStrings

        Bases: AbstractProxyModel

        Base proxy to filter a pandas DataFrame based on a calculated boolean index.

        Subclasses implement compute_filter, returning a boolean mask (one entry per source row) or None to show all rows. Mappings in both directions are then calculated with NumPy.

        Faster than the row-based SortFilterProxyModel approach, and it doesn't need a copy of the DataFrame: only the mapping arrays are built.

        The mask is recomputed whenever the source model changes its structure (reset, layout change such as sorting, inserted / removed / moved rows or columns).

        Note: the DataFrame is taken from the innermost source model, so these proxies must sit directly on top of a DataFrame model (they can't be chained).

        Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
        class BasePandasIndexFilterProxyModel(core.AbstractProxyModel):
            """Base proxy to filter a pandas DataFrame based on a calculated boolean index.
        
            Subclasses implement `compute_filter`, returning a boolean mask (one entry per
            source row) or None to show all rows. Mappings in both directions are then
            calculated with NumPy.
        
            Faster than the row-based SortFilterProxyModel approach, and it doesn't need a
            copy of the DataFrame: only the mapping arrays are built.
        
            The mask is recomputed whenever the source model changes its structure (reset,
            layout change such as sorting, inserted / removed / moved rows or columns).
        
            Note: the DataFrame is taken from the innermost source model, so these proxies
            must sit directly on top of a DataFrame model (they can't be chained).
            """
        
            def __init__(self, **kwargs):
                self._filter_index = np.ones(0, dtype=bool)
                self._source_to_proxy = np.zeros(0, dtype=np.intp)
                self._proxy_to_source = np.zeros(0, dtype=np.intp)
                self._row_count = 0
                self._connections: list[tuple[Any, Any]] = []
                super().__init__(**kwargs)
        
            # --- filter computation ---
        
            def compute_filter(self, df: pd.DataFrame) -> np.ndarray | None:
                """Return a boolean mask with one entry per row, or None for "show all"."""
                return None
        
            def get_df(self) -> pd.DataFrame | None:
                source = self.get_source_model(skip_proxies=True)
                return getattr(source, "df", None)
        
            def invalidate_filter(self):
                """Recompute the filter mask and reset the proxy."""
                with self.reset_model():
                    self._apply_filter()
        
            def _apply_filter(self):
                source = self.sourceModel()
                rowcount = source.rowCount() if source is not None else 0
                mask = None
                df = self.get_df()
                if df is not None and rowcount:
                    try:
                        mask = self.compute_filter(df)
                    except Exception:
                        logger.exception("Filtering failed, showing no rows")
                        mask = np.zeros(rowcount, dtype=bool)
                if mask is None:
                    mask = np.ones(rowcount, dtype=bool)
                mask = np.asarray(mask, dtype=bool)
                if len(mask) != rowcount:
                    logger.warning("Filter mask has %s entries for %s rows", len(mask), rowcount)
                    mask = np.zeros(rowcount, dtype=bool)
                self._filter_index = mask
                self._source_to_proxy = np.cumsum(mask) - 1
                self._proxy_to_source = np.flatnonzero(mask)
                self._row_count = len(self._proxy_to_source)
        
            # --- source model handling ---
        
            def setSourceModel(self, model):
                for signal, slot in self._connections:
                    signal.disconnect(slot)
                self._connections = []
                with self.reset_model():
                    super().setSourceModel(model)
                    self._apply_filter()
                if model is None:
                    return
                for about_to, done in _STRUCTURE_SIGNALS:
                    self._connect(getattr(model, about_to), self._on_source_about_to_change)
                    self._connect(getattr(model, done), self._on_source_changed)
                self._connect(model.dataChanged, self._on_source_data_changed)
                self._connect(model.headerDataChanged, self._on_source_header_changed)
        
            def _connect(self, signal, slot):
                signal.connect(slot)
                self._connections.append((signal, slot))
        
            def _on_source_about_to_change(self, *_args):
                self.beginResetModel()
        
            def _on_source_changed(self, *_args):
                self._apply_filter()
                self.endResetModel()
        
            def _on_source_data_changed(
                self,
                top_left: core.ModelIndex,
                bottom_right: core.ModelIndex,
                roles: Sequence[int] = (),
            ):
                first, last = top_left.row(), bottom_right.row()
                visible = np.flatnonzero(self._filter_index[first : last + 1])
                if not len(visible):
                    return
                top = int(self._source_to_proxy[first + visible[0]])
                bottom = int(self._source_to_proxy[first + visible[-1]])
                self.dataChanged.emit(
                    self.index(top, top_left.column()),
                    self.index(bottom, bottom_right.column()),
                    list(roles),
                )
        
            def _on_source_header_changed(
                self, orientation: constants.Orientation, first: int, last: int
            ):
                if orientation == constants.HORIZONTAL:
                    self.headerDataChanged.emit(orientation, first, last)
                elif self._row_count:
                    self.headerDataChanged.emit(orientation, 0, self._row_count - 1)
        
            # --- QAbstractItemModel interface ---
        
            def rowCount(self, parent: core.ModelIndex | None = None) -> int:
                if parent is not None and parent.isValid():
                    return 0
                return self._row_count
        
            def columnCount(self, parent: core.ModelIndex | None = None) -> int:
                source = self.sourceModel()
                if source is None or (parent is not None and parent.isValid()):
                    return 0
                return source.columnCount()
        
            def hasChildren(self, parent: core.ModelIndex | None = None) -> bool:
                if parent is not None and parent.isValid():
                    return False
                return self.rowCount() > 0 and self.columnCount() > 0
        
            def index(
                self, row: int, column: int, parent: core.ModelIndex | None = None
            ) -> core.ModelIndex:
                if (parent is not None and parent.isValid()) or not (
                    0 <= row < self._row_count and 0 <= column < self.columnCount()
                ):
                    return core.ModelIndex()
                return self.createIndex(row, column)
        
            def parent(self, *args):
                if args:  # parent(index): a flat table, so there is never a parent index
                    return core.ModelIndex()
                return super().parent()  # QObject.parent()
        
            def headerData(
                self,
                section: int,
                orientation: constants.Orientation,
                role: constants.ItemDataRole = constants.DISPLAY_ROLE,
            ):
                """Map header data to proxy by using proxy-to-source-map."""
                source = self.sourceModel()
                if source is None:
                    return None
                if orientation == constants.HORIZONTAL:
                    return source.headerData(section, orientation, role)
                if not 0 <= section < self._row_count:
                    return None
                return source.headerData(int(self._proxy_to_source[section]), orientation, role)
        
            def mapToSource(self, proxy_idx: core.ModelIndex) -> core.ModelIndex:
                """Map index to source by using proxy-to-source map."""
                source = self.sourceModel()
                if (
                    source is None
                    or not proxy_idx.isValid()
                    or not 0 <= proxy_idx.row() < self._row_count
                ):
                    return core.ModelIndex()
                row_pos = int(self._proxy_to_source[proxy_idx.row()])
                return source.index(row_pos, proxy_idx.column())
        
            def mapFromSource(self, source_index: core.ModelIndex) -> core.ModelIndex:
                row = source_index.row()
                if (
                    self.sourceModel() is None
                    or not source_index.isValid()
                    or not 0 <= row < len(self._filter_index)
                    or not self._filter_index[row]  # filtered out: no proxy index
                ):
                    return core.ModelIndex()
                return self.index(int(self._source_to_proxy[row]), source_index.column())
        

        compute_filter

        compute_filter(df: DataFrame) -> ndarray | None
        

        Return a boolean mask with one entry per row, or None for "show all".

        Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
        def compute_filter(self, df: pd.DataFrame) -> np.ndarray | None:
            """Return a boolean mask with one entry per row, or None for "show all"."""
            return None
        

        headerData

        headerData(section: int, orientation: Orientation, role: ItemDataRole = DISPLAY_ROLE)
        

        Map header data to proxy by using proxy-to-source-map.

        Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
        def headerData(
            self,
            section: int,
            orientation: constants.Orientation,
            role: constants.ItemDataRole = constants.DISPLAY_ROLE,
        ):
            """Map header data to proxy by using proxy-to-source-map."""
            source = self.sourceModel()
            if source is None:
                return None
            if orientation == constants.HORIZONTAL:
                return source.headerData(section, orientation, role)
            if not 0 <= section < self._row_count:
                return None
            return source.headerData(int(self._proxy_to_source[section]), orientation, role)
        

        invalidate_filter

        invalidate_filter()
        

        Recompute the filter mask and reset the proxy.

        Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
        def invalidate_filter(self):
            """Recompute the filter mask and reset the proxy."""
            with self.reset_model():
                self._apply_filter()
        

        mapToSource

        mapToSource(proxy_idx: ModelIndex) -> ModelIndex
        

        Map index to source by using proxy-to-source map.

        Source code in src/cutepandas/pandasmodels/pandasindexfilterproxymodel.py
        def mapToSource(self, proxy_idx: core.ModelIndex) -> core.ModelIndex:
            """Map index to source by using proxy-to-source map."""
            source = self.sourceModel()
            if (
                source is None
                or not proxy_idx.isValid()
                or not 0 <= proxy_idx.row() < self._row_count
            ):
                return core.ModelIndex()
            row_pos = int(self._proxy_to_source[proxy_idx.row()])
            return source.index(row_pos, proxy_idx.column())
        

        :fa-brands-github: Show source on GitHub