Skip to content

ColumnProfileWidget

Base classes

Name Children Inherits
TranslateMixin
cutepandas.utils.i18n
Keeps an optional `translate` callable; `_tr(text)` applies it.
Widget
prettyqt.widgets.widget
The base class of all user interface objects.

⋔ Inheritance diagram

graph TD
  696186303["columnprofilewidget.ColumnProfileWidget"]
  3771062457["i18n.TranslateMixin"]
  2751680898["builtins.object"]
  3664736470["widgets.Widget"]
  829357528["widgets.WidgetMixin"]
  3227531497["core.ObjectMixin"]
  625385617["gui.PaintDeviceMixin"]
  1348938779["QtWidgets.QWidget"]
  13951691["QtCore.QObject"]
  395147830["sip.wrapper"]
  46922758["sip.simplewrapper"]
  2007623938["QtGui.QPaintDevice"]
  3771062457 --> 696186303
  2751680898 --> 3771062457
  3664736470 --> 696186303
  829357528 --> 3664736470
  3227531497 --> 829357528
  2751680898 --> 3227531497
  625385617 --> 829357528
  2751680898 --> 625385617
  1348938779 --> 3664736470
  13951691 --> 1348938779
  395147830 --> 13951691
  46922758 --> 395147830
  2751680898 --> 46922758
  2007623938 --> 1348938779
  46922758 --> 2007623938

🛈 DocStrings

Bases: TranslateMixin, Widget

Basic statistics and the most frequent values of one column of any frame.

Shows dtype, row / null / unique counts, min / max / mean / std and the top values with a share bar.

set_column() computes the statistics right away (FrameSource.describe, a full column scan). For large frames compute them in a worker thread and pass the result to set_stats(), which must run on the GUI thread.

The field labels (FIELDS) and the top values header go through translate (str -> str, e.g. gettext); set_translate() / retranslate() switch the language at runtime (see cutepandas.utils.i18n).

Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
class ColumnProfileWidget(TranslateMixin, widgets.Widget):
    """Basic statistics and the most frequent values of one column of any frame.

    Shows dtype, row / null / unique counts, min / max / mean / std and the top values
    with a share bar.

    `set_column()` computes the statistics right away (`FrameSource.describe`, a full
    column scan). For large frames compute them in a worker thread and pass the
    result to `set_stats()`, which must run on the GUI thread.

    The field labels (`FIELDS`) and the top values header go through `translate`
    (`str -> str`, e.g. gettext); `set_translate()` / `retranslate()` switch the
    language at runtime (see `cutepandas.utils.i18n`).
    """

    FIELDS: ClassVar = (
        N_("Rows"),
        N_("Nulls"),
        N_("Unique"),
        N_("Min"),
        N_("Max"),
        N_("Mean"),
        N_("Std"),
    )

    def __init__(
        self,
        df: Any = None,
        column: Any = None,
        *,
        top: int = 10,
        translate: Translate | None = None,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self._translate = translate
        self.top = top
        layout = self.set_layout("vertical", margin=4)
        self.title = widgets.Label()
        self.title.setTextFormat(constants.TextFormat.RichText)
        layout.add(self.title)
        form = widgets.FormLayout()
        self.value_labels: dict[str, widgets.Label] = {}
        self.field_labels: dict[str, widgets.Label] = {}
        for name in self.FIELDS:
            label = widgets.Label()
            label.set_text_interaction("by_mouse")
            self.value_labels[name] = label
            self.field_labels[name] = widgets.Label()
            form.addRow(self.field_labels[name], label)
        layout.add(form)
        self.top_table = widgets.TableView(selection_behavior="rows")
        self.top_table.v_header.hide()
        self.top_table.set_delegate(ValueColorDelegate(mode="bar"), column=2)
        layout.add(self.top_table)
        self.retranslate()
        self.clear()
        if df is not None and column is not None:
            self.set_column(df, column)

    def retranslate(self):
        """Re-show the labels with the current `translate` callable."""
        for name, label in self.field_labels.items():
            label.set_text(f"{self._tr(name)}:")
        if isinstance(model := self.top_table.model(), TopValuesModel):
            model.set_translate(self._translate)

    def clear(self):
        self.title.set_text("")
        for label in self.value_labels.values():
            label.set_text("")
        self.top_table.set_model(
            TopValuesModel(translate=self._translate, parent=self.top_table)
        )

    def set_column(self, df: Any, column: Any):
        """Profile a column (position or label) of a frame, source or holder."""
        source = df.source if isinstance(df, DataFrameHolder) else as_source(df)
        if source is None:
            self.clear()
            return
        pos = self._position(source, column)
        self.set_stats(source.columns[pos], source.describe(pos, top=self.top))

    @staticmethod
    def _position(source: FrameSource, column: Any) -> int:
        names = [info.name for info in source.columns]
        if column in names:
            return names.index(column)
        if isinstance(column, int) and 0 <= column < len(names):
            return column
        msg = f"No column {column!r}"
        raise KeyError(msg)

    def set_stats(self, info: ColumnInfo, stats: ColumnStats):
        """Show precomputed statistics (GUI thread)."""
        self.title.set_text(f"<b>{info.label}</b> &nbsp; {info.dtype}")
        self.setWindowIcon(icons.icon_for_kind(info.kind))
        share = f" ({stats.null_count / stats.count:.1%})" if stats.count else ""
        values = {
            "Rows": str(stats.count),
            "Nulls": f"{stats.null_count}{share}",
            "Unique": _fmt(stats.unique),
            "Min": _fmt(stats.min),
            "Max": _fmt(stats.max),
            "Mean": _fmt(stats.mean),
            "Std": _fmt(stats.std),
        }
        for name, text in values.items():
            self.value_labels[name].set_text(text)
        old = self.top_table.model()
        self.top_table.set_model(
            TopValuesModel(stats.top, stats.count, translate=self._translate, parent=self)
        )
        if old is not None:
            old.deleteLater()

retranslate

retranslate()

Re-show the labels with the current translate callable.

Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
def retranslate(self):
    """Re-show the labels with the current `translate` callable."""
    for name, label in self.field_labels.items():
        label.set_text(f"{self._tr(name)}:")
    if isinstance(model := self.top_table.model(), TopValuesModel):
        model.set_translate(self._translate)

set_column

set_column(df: Any, column: Any)

Profile a column (position or label) of a frame, source or holder.

Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
def set_column(self, df: Any, column: Any):
    """Profile a column (position or label) of a frame, source or holder."""
    source = df.source if isinstance(df, DataFrameHolder) else as_source(df)
    if source is None:
        self.clear()
        return
    pos = self._position(source, column)
    self.set_stats(source.columns[pos], source.describe(pos, top=self.top))

set_stats

set_stats(info: ColumnInfo, stats: ColumnStats)

Show precomputed statistics (GUI thread).

Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
def set_stats(self, info: ColumnInfo, stats: ColumnStats):
    """Show precomputed statistics (GUI thread)."""
    self.title.set_text(f"<b>{info.label}</b> &nbsp; {info.dtype}")
    self.setWindowIcon(icons.icon_for_kind(info.kind))
    share = f" ({stats.null_count / stats.count:.1%})" if stats.count else ""
    values = {
        "Rows": str(stats.count),
        "Nulls": f"{stats.null_count}{share}",
        "Unique": _fmt(stats.unique),
        "Min": _fmt(stats.min),
        "Max": _fmt(stats.max),
        "Mean": _fmt(stats.mean),
        "Std": _fmt(stats.std),
    }
    for name, text in values.items():
        self.value_labels[name].set_text(text)
    old = self.top_table.model()
    self.top_table.set_model(
        TopValuesModel(stats.top, stats.count, translate=self._translate, parent=self)
    )
    if old is not None:
        old.deleteLater()

:fa-brands-github: Show source on GitHub