Skip to content

Commit

Permalink
support polars and xarray
Browse files Browse the repository at this point in the history
  • Loading branch information
hanjinliu committed Jan 9, 2023
1 parent 10b3b27 commit 9239de0
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 25 deletions.
5 changes: 4 additions & 1 deletion tabulous/widgets/_mainwindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,10 @@ def _normalize_widget(widget: Widget | QWidget, name: str) -> tuple[QWidget, str
def _copy_dataframe(data) -> pd.DataFrame:
import pandas as pd

return pd.DataFrame(data, copy=True)
if isinstance(data, pd.DataFrame):
return data.copy()
else:
return Table._normalize_data(data)


def _find_parent_table(qwidget: _QtMainWidgetBase) -> TableViewerBase:
Expand Down
78 changes: 54 additions & 24 deletions tabulous/widgets/_table.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import logging
from abc import ABC, abstractmethod
from abc import ABC, abstractmethod, abstractstaticmethod
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Hashable, TYPE_CHECKING, overload
Expand Down Expand Up @@ -179,7 +179,7 @@ def _emit_data_changed_signal(self, info: ItemInfo) -> None:
def _create_backend(self, data: pd.DataFrame) -> QBaseTable:
"""This function creates a backend widget."""

@abstractmethod
@abstractstaticmethod
def _normalize_data(self, data):
"""Data normalization before setting a new data."""

Expand Down Expand Up @@ -328,24 +328,6 @@ def move_iloc(self, row: int | None, column: int | None, scroll: bool = True):
qtable_view.scrollTo(index)
return None

def foreground_colormap(self, *args, **kwargs):
"""Deprecated method."""
warnings.warn(
"Method `table.foreground_colormap` is deprecated. "
"Use `table.text_color.set` instead.",
DeprecationWarning,
)
return self.text_color.set(*args, **kwargs)

def background_colormap(self, *args, **kwargs):
"""Deprecated method."""
warnings.warn(
"Method `table.background_colormap` is deprecated. "
"Use `table.background_color.set` instead.",
DeprecationWarning,
)
return self.background_color.set(*args, **kwargs)

text_formatter = formatter # alias

@property
Expand Down Expand Up @@ -609,11 +591,30 @@ class _DataFrameTableLayer(TableBase):
_qwidget: QTableLayer | QSpreadSheet
native: QTableLayer | QSpreadSheet

def _normalize_data(self, data) -> pd.DataFrame:
@staticmethod
def _normalize_data(data) -> pd.DataFrame:
import pandas as pd

if not isinstance(data, pd.DataFrame):
data = pd.DataFrame(data)
mod = type(data).__module__.split(".", 1)[0]
if mod == "polars":
import polars as pl

if isinstance(data, pl.DataFrame):
data = data.to_pandas()
elif isinstance(data, pl.Series):
data = pd.DataFrame(data.to_pandas())
else:
raise TypeError(f"{type(data)} cannot be converted.")
elif mod == "xarray" and hasattr(data, "to_dataframe"):
import xarray as xr

if isinstance(data, xr.DataArray):
data = data.to_dataframe("val").reset_index()
else:
raise TypeError(f"{type(data)} cannot be converted.")
else:
data = pd.DataFrame(data)
return data

def assign(self, other: dict[str, Any] = {}, **kwargs: dict[str, Any]) -> Self:
Expand Down Expand Up @@ -759,7 +760,8 @@ def _create_backend(self, data: pd.DataFrame) -> QTableGroupBy:

return QTableGroupBy(data=data)

def _normalize_data(self, data):
@staticmethod
def _normalize_data(data):
import pandas as pd
from pandas.core.groupby.generic import DataFrameGroupBy

Expand Down Expand Up @@ -813,7 +815,8 @@ def _create_backend(self, data: Callable[[], Any]) -> QTableDisplay:

return QTableDisplay(loader=data)

def _normalize_data(self, data):
@staticmethod
def _normalize_data(data):
if not callable(data):
raise TypeError("Can only add callable object.")
return data
Expand Down Expand Up @@ -847,3 +850,30 @@ def running(self) -> bool:
@running.setter
def running(self, value: bool) -> None:
return self._qwidget.setRunning(value)


# deprecations


def foreground_colormap(self: TableBase, *args, **kwargs):
"""Deprecated method."""
warnings.warn(
"Method `table.foreground_colormap` is deprecated. "
"Use `table.text_color.set` instead.",
DeprecationWarning,
)
return self.text_color.set(*args, **kwargs)


def background_colormap(self: TableBase, *args, **kwargs):
"""Deprecated method."""
warnings.warn(
"Method `table.background_colormap` is deprecated. "
"Use `table.background_color.set` instead.",
DeprecationWarning,
)
return self.background_color.set(*args, **kwargs)


TableBase.foreground_colormap = foreground_colormap
TableBase.background_colormap = background_colormap

0 comments on commit 9239de0

Please sign in to comment.