Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`:

Expand Down
1 change: 1 addition & 0 deletions README.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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()`:

Expand Down
1 change: 1 addition & 0 deletions docs/_quarto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ quartodoc:
- pin_versions_prune
- pin_delete
- pin_search
- df_library

filters:
- interlinks
Expand Down
47 changes: 44 additions & 3 deletions docs/get_started.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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


Expand Down
45 changes: 41 additions & 4 deletions pins/_adaptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,22 @@

if TYPE_CHECKING:
import pandas as pd
import polars as pl

Check failure on line 12 in pins/_adaptors.py

View workflow job for this annotation

GitHub Actions / Run Pyright

Import "polars" could not be resolved (reportMissingImports)

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:
Expand Down Expand Up @@ -70,8 +76,6 @@


class DFAdaptor(Adaptor):
_d: ClassVar[DataFrame]

def __init__(self, data: DataFrame) -> None:
super().__init__(data)

Expand Down Expand Up @@ -142,13 +146,46 @@
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
def create_adaptor(obj: Any) -> Adaptor: ...

Check failure on line 183 in pins/_adaptors.py

View workflow job for this annotation

GitHub Actions / Run Pyright

Overload 2 for "create_adaptor" will never be used because its parameters overlap overload 1 (reportOverlappingOverload)
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:
Expand Down
38 changes: 35 additions & 3 deletions pins/boards.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 --------------------------------------------
Expand Down
19 changes: 19 additions & 0 deletions pins/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from __future__ import annotations

import os
from types import SimpleNamespace
from typing import Literal, cast, get_args

import appdirs

Expand All @@ -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)

Expand Down Expand Up @@ -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)
48 changes: 26 additions & 22 deletions pins/drivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -43,6 +48,7 @@
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
Expand All @@ -53,6 +59,9 @@
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
Expand All @@ -67,32 +76,27 @@
)

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

Check failure on line 81 in pins/drivers.py

View workflow job for this annotation

GitHub Actions / Run Pyright

Import "polars" could not be resolved (reportMissingImports)

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)
Expand Down
27 changes: 27 additions & 0 deletions pins/tests/test_boards.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading