Skip to content

PandasColumnListModel

Base classes

Name Children Inherits
SchemaModel
cutepandas.pandasmodels.schemamodel
One row per column of a frame (any backend), read-only.

⋔ Inheritance diagram

graph TD
  1775412234["pandascolumnlistmodel.PandasColumnListModel"]
  1331296928["schemamodel.SchemaModel"]
  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"]
  1331296928 --> 1775412234
  1559661765 --> 1331296928
  3771062457 --> 1559661765
  2751680898 --> 3771062457
  103874424 --> 1331296928
  2751680898 --> 103874424
  3514613245 --> 1331296928
  2751680898 --> 3514613245
  656210031 --> 1331296928
  4092674192 --> 656210031
  3882849576 --> 4092674192
  3227531497 --> 3882849576
  2751680898 --> 3227531497
  1115338939 --> 656210031
  930985301 --> 1115338939
  13951691 --> 930985301
  395147830 --> 13951691
  46922758 --> 395147830
  2751680898 --> 46922758

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub