diff --git a/README.md b/README.md index 31955ddb..32768c66 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ board.pin_write(mtcars.head(), "mtcars", type="csv") Above, we saved the data as a CSV, but depending on what you’re saving and who else you want to read it, you might use the `type` argument to instead save it as a `joblib`, `parquet`, or `json` file. +You can pin [polars](https://pola.rs/) DataFrames too, by installing +`pins[polars]`. You can later retrieve the pinned data with `.pin_read()`: diff --git a/README.qmd b/README.qmd index 98af5826..61f40106 100644 --- a/README.qmd +++ b/README.qmd @@ -66,6 +66,7 @@ board.pin_write(mtcars.head(), "mtcars", type="csv") Above, we saved the data as a CSV, but depending on what you’re saving and who else you want to read it, you might use the `type` argument to instead save it as a `joblib`, `parquet`, or `json` file. +You can pin [polars](https://pola.rs/) DataFrames too, by installing `pins[polars]`. You can later retrieve the pinned data with `.pin_read()`: diff --git a/docs/_quarto.yml b/docs/_quarto.yml index afb51204..a612a60e 100644 --- a/docs/_quarto.yml +++ b/docs/_quarto.yml @@ -121,6 +121,7 @@ quartodoc: - pin_versions_prune - pin_delete - pin_search + - df_library filters: - interlinks diff --git a/docs/get_started.qmd b/docs/get_started.qmd index 4b8096fb..9a86a7ca 100644 --- a/docs/get_started.qmd +++ b/docs/get_started.qmd @@ -72,12 +72,14 @@ If you are using the Posit Connect board [](`~pins.board_connect`), then you mus Above, we saved the data as a CSV, but you can choose another option depending on your goals: -- `type = "csv"` uses `to_csv()` from pandas to create a CSV file. CSVs are plain text and can be read easily by many applications, but they only support simple columns (e.g. numbers, strings), can take up a lot of disk space, and can be slow to read. -- `type = "parquet"` uses `to_parquet()` from pandas to create a Parquet file. [Parquet](https://parquet.apache.org/) is a modern, language-independent, column-oriented file format for efficient data storage and retrieval. Parquet is an excellent choice for storing tabular data. -- `type = "arrow"` uses `to_feather()` from pandas to create an Arrow/Feather file. +- `type = "csv"` creates a CSV file. CSVs are plain text and can be read easily by many applications, but they only support simple columns (e.g. numbers, strings), can take up a lot of disk space, and can be slow to read. +- `type = "parquet"` creates a Parquet file. [Parquet](https://parquet.apache.org/) is a modern, language-independent, column-oriented file format for efficient data storage and retrieval. Parquet is an excellent choice for storing tabular data. +- `type = "arrow"` creates an Arrow/Feather file. - `type = "joblib"` uses `joblib.dump()` to create a binary Python data file, such as for storing a trained model. See the [joblib docs](https://joblib.readthedocs.io/en/latest/) for more information. - `type = "json"` uses `json.dump()` to create a JSON file. Pretty much every programming language can read JSON files, but they only work well for nested lists. +The `csv`, `parquet`, and `arrow` types work with both pandas and [polars](https://pola.rs/) DataFrames; see [Using polars](#using-polars). + Note that when the data lives elsewhere, pins takes care of downloading and caching so that it's only re-downloaded when needed. That said, most boards transmit pins over HTTP, and this is going to be slow and possibly unreliable for very large pins. As a general rule of thumb, we don't recommend using pins with files over 500 MB. @@ -88,6 +90,45 @@ Storing your data/object as a pin works well when you write from a single source - **Good** use for pins: an ETL pipeline that stores a model or summarized dataset once a day - **Bad** use for pins: a Shiny app that collects data from users, who may be using the app at the same time +## Using polars + +pins can read and write [polars](https://pola.rs/) DataFrames as well as pandas DataFrames. +Install pins with the polars extra to get a supported version of polars: + +```bash +python -m pip install "pins[polars]" +``` + +To write a polars DataFrame, pass it to [](`~pins.boards.BaseBoard.pin_write`) with `type="csv"`, `"parquet"`, or `"arrow"`. +pins detects that it is a polars DataFrame, so you don't need any extra arguments: + +```{python} +import polars as pl + +board_pl = board_temp() +board_pl.pin_write(pl.from_pandas(mtcars), "mtcars-pl", type="parquet") +``` + +By default, [](`~pins.boards.BaseBoard.pin_read`) returns tabular pins as pandas DataFrames, no matter which library wrote them. +To read them as polars DataFrames instead, set `df_library` on the board: + +```{python} +board_pl.df_library = "polars" +board_pl.pin_read("mtcars-pl") +``` + +You can also set the `PINS_DF_LIBRARY` environment variable to `"polars"` to make polars the default for every board. +If both are set, the board's `df_library` takes precedence. + +Because pins stores data in standard file formats, a pin written from pandas can be read into polars, and the reverse. +Use `type="parquet"` or `type="arrow"` for pins shared between libraries: +these formats keep column types such as dates and datetimes, while a CSV reads them back as strings. + +::: {.callout-note} +Arrow files written from polars use newer Arrow string types. +Reading them with pandas requires pyarrow 16 or later, and reading them from R requires a recent version of the arrow package. +::: + ## Metadata diff --git a/pins/_adaptors.py b/pins/_adaptors.py index 80fb9f68..83df9441 100644 --- a/pins/_adaptors.py +++ b/pins/_adaptors.py @@ -9,16 +9,22 @@ if TYPE_CHECKING: import pandas as pd + import polars as pl PandasDataFrame: TypeAlias = pd.DataFrame - DataFrame: TypeAlias = PandasDataFrame + PolarsDataFrame: TypeAlias = pl.DataFrame + DataFrame: TypeAlias = "PandasDataFrame | PolarsDataFrame" class AbstractPandasFrame(AbstractBackend): _backends = [("pandas", "DataFrame")] -AbstractDF: TypeAlias = AbstractPandasFrame +class AbstractPolarsFrame(AbstractBackend): + _backends = [("polars", "DataFrame")] + + +AbstractDF: TypeAlias = "AbstractPandasFrame | AbstractPolarsFrame" class Adaptor: @@ -70,8 +76,6 @@ def _obj_name(self) -> str: class DFAdaptor(Adaptor): - _d: ClassVar[DataFrame] - def __init__(self, data: DataFrame) -> None: super().__init__(data) @@ -142,6 +146,37 @@ def write_feather(self, file: str) -> None: self._d.to_feather(file) +class PolarsAdaptor(DFAdaptor): + _d: ClassVar[PolarsDataFrame] + + def __init__(self, data: AbstractPolarsFrame) -> None: + super().__init__(data) + + @property + def columns(self) -> list[Any]: + return self._d.columns + + @property + def shape(self) -> tuple[int, int]: + return self._d.shape + + def head(self, n: int) -> PolarsAdaptor: + return PolarsAdaptor(self._d.head(n)) + + def to_json(self) -> str: + return self._d.write_json() + + def write_csv(self, file: str) -> None: + self._d.write_csv(file) + + def write_parquet(self, file: str) -> None: + self._d.write_parquet(file) + + def write_feather(self, file: str) -> None: + # uses Arrow string_view, so readers need pyarrow>=16 or a recent R arrow + self._d.write_ipc(file) + + @overload def create_adaptor(obj: DataFrame) -> DFAdaptor: ... @overload @@ -149,6 +184,8 @@ def create_adaptor(obj: Any) -> Adaptor: ... def create_adaptor(obj: Any | DataFrame) -> Adaptor | DFAdaptor: if isinstance(obj, AbstractPandasFrame): return PandasAdaptor(obj) + elif isinstance(obj, AbstractPolarsFrame): + return PolarsAdaptor(obj) elif isinstance(obj, Adaptor): return obj else: diff --git a/pins/boards.py b/pins/boards.py index d19b19d0..22cc8f8f 100644 --- a/pins/boards.py +++ b/pins/boards.py @@ -18,7 +18,7 @@ from ._adaptors import Adaptor, create_adaptor from .cache import PinsCache -from .config import get_allow_rsc_short_name +from .config import DFLibrary, get_allow_rsc_short_name, get_df_library from .drivers import REQUIRES_SINGLE_FILE, default_title, load_data, load_file, save_data from .errors import PinsError, PinsVersionError from .meta import Meta, MetaFactory, MetaRaw @@ -66,6 +66,28 @@ def __init__( self.meta_factory = meta_factory self.versioned = versioned self.allow_pickle_read = allow_pickle_read + self._df_library: DFLibrary | None = None + + @property + def df_library(self) -> DFLibrary | None: + """DataFrame library that `pin_read` uses for "csv", "arrow", and "parquet" pins. + + Either "pandas" or "polars". If `None`, uses the `PINS_DF_LIBRARY` + environment variable, or "pandas" if that is unset. + + Examples + -------- + >>> from pins import board_temp + >>> board = board_temp() + >>> board.df_library = "polars" + """ + return self._df_library + + @df_library.setter + def df_library(self, value: DFLibrary | None) -> None: + if value is not None: + get_df_library(value) + self._df_library = value def pin_exists(self, name: str) -> bool: """Determine if a pin exists. @@ -203,6 +225,12 @@ def pin_read(self, name, version: str | None = None, hash: str | None = None): A hash used to validate the retrieved pin data. If specified, it is compared against the `pin_hash` field retrieved by [](`~pins.boards.BaseBoard.pin_meta`). + Notes + ----- + Pins of type "csv", "arrow", and "parquet" are returned as pandas DataFrames + by default. Set [](`~pins.boards.BaseBoard.df_library`) on the board, or the + `PINS_DF_LIBRARY` environment variable, to "polars" to return polars DataFrames. + """ meta = self.pin_fetch(name, version) @@ -355,7 +383,7 @@ def pin_write( Parameters ---------- x: - An object (e.g. a pandas DataFrame) to pin. + An object (e.g. a pandas or polars DataFrame) to pin. name: Pin name. type: @@ -785,7 +813,11 @@ def _extract_search_meta(self, meta): def _load_data(self, meta, pin_version_path): """Return the data object stored by a pin (e.g. a DataFrame).""" return load_data( - meta, self.fs, pin_version_path, allow_pickle_read=self.allow_pickle_read + meta, + self.fs, + pin_version_path, + allow_pickle_read=self.allow_pickle_read, + df_library=self.df_library, ) # filesystem and cache methods -------------------------------------------- diff --git a/pins/config.py b/pins/config.py index 8330eafe..d5119291 100644 --- a/pins/config.py +++ b/pins/config.py @@ -1,5 +1,8 @@ +from __future__ import annotations + import os from types import SimpleNamespace +from typing import Literal, cast, get_args import appdirs @@ -9,6 +12,10 @@ PINS_ENV_INSECURE_READ = "PINS_ALLOW_PICKLE_READ" PINS_ENV_ALLOW_RSC_SHORT_NAME = "PINS_ALLOW_RSC_SHORT_NAME" PINS_ENV_FEATURE_PREVIEW = "PINS_FEATURE_PREVIEW" +PINS_ENV_DF_LIBRARY = "PINS_DF_LIBRARY" + +DFLibrary = Literal["pandas", "polars"] +DF_LIBRARIES: tuple[DFLibrary, ...] = get_args(DFLibrary) pins_options = SimpleNamespace(quiet=False) @@ -47,3 +54,15 @@ def get_allow_rsc_short_name(): def get_feature_preview(): return _interpret_int(PINS_ENV_FEATURE_PREVIEW) + + +def get_df_library(df_library: str | None) -> DFLibrary: + if df_library is None: + df_library = os.environ.get(PINS_ENV_DF_LIBRARY, "pandas") + + if df_library not in DF_LIBRARIES: + raise ValueError( + f"df_library must be one of {DF_LIBRARIES}, but was {repr(df_library)}." + ) + + return cast(DFLibrary, df_library) diff --git a/pins/drivers.py b/pins/drivers.py index 2b5a0045..c1cda509 100644 --- a/pins/drivers.py +++ b/pins/drivers.py @@ -4,7 +4,12 @@ from pins._adaptors import Adaptor, create_adaptor -from .config import PINS_ENV_INSECURE_READ, get_allow_pickle_read +from .config import ( + PINS_ENV_INSECURE_READ, + DFLibrary, + get_allow_pickle_read, + get_df_library, +) from .errors import PinsInsecureReadError from .meta import Meta @@ -43,6 +48,7 @@ def load_data( fs, path_to_version: "str | None" = None, allow_pickle_read: "bool | None" = None, + df_library: "DFLibrary | None" = None, ): """Return loaded data, based on meta type. Parameters @@ -53,6 +59,9 @@ def load_data( An abstract filesystem with a method to .open() files. path_to_version: A filepath used as the parent directory the data to-be-loaded lives in. + df_library: + The DataFrame library ("pandas" or "polars") used to read table types. + Defaults to the PINS_DF_LIBRARY environment variable, or "pandas". """ # TODO: extandable loading with deferred importing @@ -67,32 +76,27 @@ def load_data( ) with load_file(meta.file, fs, path_to_version, meta.type) as f: - if meta.type == "csv": - import pandas as pd - - return pd.read_csv(f) - - elif meta.type == "arrow": - import pandas as pd - - return pd.read_feather(f) - - elif meta.type == "feather": - import pandas as pd - - return pd.read_feather(f) - - elif meta.type == "parquet": - import pandas as pd + if meta.type in ("csv", "table", "arrow", "feather", "parquet"): + if get_df_library(df_library) == "polars": + import polars as pl - return pd.read_parquet(f) + if meta.type in ("csv", "table"): + return pl.read_csv(f) + elif meta.type in ("arrow", "feather"): + return pl.read_ipc(f) + else: + return pl.read_parquet(f) - elif meta.type == "table": import pandas as pd - return pd.read_csv(f) + if meta.type in ("csv", "table"): + return pd.read_csv(f) + elif meta.type in ("arrow", "feather"): + return pd.read_feather(f) + else: + return pd.read_parquet(f) - elif meta.type == "joblib": + if meta.type == "joblib": import joblib return joblib.load(f) diff --git a/pins/tests/test_boards.py b/pins/tests/test_boards.py index ea24acda..fb46efc1 100644 --- a/pins/tests/test_boards.py +++ b/pins/tests/test_boards.py @@ -104,6 +104,33 @@ def test_board_pin_write_roundtrip(board): assert loaded_df.equals(df) +def test_board_pin_write_roundtrip_polars(): + import polars as pl + + from pins import board_temp + + board = board_temp() + board.df_library = "polars" + df = pl.DataFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]}) + + board.pin_write(df, "df_parquet", type="parquet") + loaded_df = board.pin_read("df_parquet") + + assert isinstance(loaded_df, pl.DataFrame) + assert loaded_df.equals(df) + + +def test_board_df_library_invalid(): + from pins import board_temp + + board = board_temp() + + with pytest.raises(ValueError, match="df_library must be one of"): + board.df_library = "spark" + + assert board.df_library is None + + @skip_if_dbc def test_board_pin_write_type_not_specified_error(board): class C: diff --git a/pins/tests/test_drivers.py b/pins/tests/test_drivers.py index 5959e028..be63baee 100644 --- a/pins/tests/test_drivers.py +++ b/pins/tests/test_drivers.py @@ -4,10 +4,11 @@ import fsspec import pandas as pd +import polars as pl import pytest from pins._adaptors import create_adaptor -from pins.config import PINS_ENV_INSECURE_READ +from pins.config import PINS_ENV_DF_LIBRARY, PINS_ENV_INSECURE_READ from pins.drivers import default_title, load_data, load_path, save_data from pins.errors import PinsInsecureReadError from pins.meta import MetaRaw @@ -37,6 +38,7 @@ class D: [ (pd.DataFrame({"x": [1, 2]}), "somename: a pinned 2 x 1 DataFrame"), (pd.DataFrame({"x": [1], "y": [2]}), "somename: a pinned 1 x 2 DataFrame"), + (pl.DataFrame({"x": [1, 2]}), "somename: a pinned 2 x 1 DataFrame"), (ExC(), "somename: a pinned ExC object"), (ExC().D(), "somename: a pinned ExC.D object"), ([1, 2, 3], "somename: a pinned list object"), @@ -79,6 +81,82 @@ def test_driver_roundtrip(tmp_path: Path, type_): assert df.equals(obj) +@pytest.mark.parametrize("type_", ["csv", "arrow", "parquet"]) +def test_driver_polars_roundtrip(tmp_path: Path, type_): + df = pl.DataFrame({"x": [1, 2, 3], "y": ["a", None, "c"]}) + + p_obj = tmp_path / "some_df" + res_fname = save_data(df, p_obj, type_) + + meta = MetaRaw(Path(res_fname).name, type_, "my_pin") + obj = load_data(meta, fsspec.filesystem("file"), tmp_path, df_library="polars") + + assert isinstance(obj, pl.DataFrame) + assert df.equals(obj) + + +@pytest.mark.parametrize("type_", ["csv", "arrow", "parquet"]) +def test_driver_df_library_env_var(tmp_path: Path, type_, monkeypatch): + df = pd.DataFrame({"x": [1, 2, 3]}) + res_fname = save_data(df, tmp_path / "some_df", type_) + meta = MetaRaw(Path(res_fname).name, type_, "my_pin") + fs = fsspec.filesystem("file") + + monkeypatch.setenv(PINS_ENV_DF_LIBRARY, "polars") + assert isinstance(load_data(meta, fs, tmp_path), pl.DataFrame) + + # an explicit value takes precedence over the env var + assert isinstance(load_data(meta, fs, tmp_path, df_library="pandas"), pd.DataFrame) + + +def test_driver_df_library_invalid(tmp_path: Path): + res_fname = save_data(pd.DataFrame({"x": [1]}), tmp_path / "some_df", "csv") + meta = MetaRaw(Path(res_fname).name, "csv", "my_pin") + + with pytest.raises(ValueError, match="df_library must be one of"): + load_data(meta, fsspec.filesystem("file"), tmp_path, df_library="spark") + + +@pytest.mark.parametrize("type_", ["csv", "arrow", "parquet"]) +@pytest.mark.parametrize("src, dst", [("pandas", "polars"), ("polars", "pandas")]) +def test_driver_cross_library_roundtrip(tmp_path: Path, type_, src, dst): + import datetime as dt + + expected = pl.DataFrame( + { + "i": [1, 2, 3], + "f": [1.5, None, 3.0], + "s": ["a", None, "c"], + "t": [dt.datetime(2024, 1, 1, 12), None, dt.datetime(2024, 1, 3)], + } + ) + if type_ == "csv": + # csv does not store types, so datetimes come back as strings + expected = expected.drop("t") + + obj = expected if src == "polars" else expected.to_pandas() + res_fname = save_data(obj, tmp_path / "some_df", type_) + + meta = MetaRaw(Path(res_fname).name, type_, "my_pin") + res = load_data(meta, fsspec.filesystem("file"), tmp_path, df_library=dst) + + if dst == "pandas": + assert isinstance(res, pd.DataFrame) + res = pl.from_pandas(res) + else: + assert isinstance(res, pl.DataFrame) + + assert res.equals(expected) + + +def test_polars_data_preview_matches_pandas(): + data = {"x": [1.5, 2.5, None], "y": ["a", "b", "c"]} + pd_preview = create_adaptor(pd.DataFrame(data)).data_preview + pl_preview = create_adaptor(pl.DataFrame(data)).data_preview + + assert pl_preview == pd_preview + + @pytest.mark.parametrize( "type_", [ diff --git a/pyproject.toml b/pyproject.toml index 57cd1405..3c469641 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,11 +54,13 @@ doc = [ "quartodoc", ] gcs = ["gcsfs"] +polars = ["polars>=1.0"] test = [ "pins[azure]", "pins[gcs]", "pins[databricks]", "pins[aws]", + "pins[polars]", "fastparquet", "pip-tools", "pyarrow", diff --git a/requirements/dev.txt b/requirements/dev.txt index 0f8fd751..31f40fe1 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -286,6 +286,10 @@ pluggy==1.6.0 # via pytest plum-dispatch==2.5.7 # via quartodoc +polars==2.2.0 + # via pins (pyproject.toml) +polars-runtime-32==2.2.0 + # via polars pre-commit==4.2.0 # via pins (pyproject.toml) prompt-toolkit==3.0.51