Skip to content

Commit

Permalink
datachain: implement to_parquet (#97)
Browse files Browse the repository at this point in the history
First part of #91, critical for the release.
It uses `to_pandas()`, so it cannot write to a parquet
file than what memory allows.
  • Loading branch information
skshetry authored Jul 20, 2024
1 parent 80672d6 commit 69597f5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/datachain/lib/dc.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import copy
import os
import re
from collections.abc import Iterable, Iterator, Sequence
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
BinaryIO,
Callable,
ClassVar,
Literal,
Expand Down Expand Up @@ -1178,6 +1180,25 @@ def from_parquet(
partitioning=partitioning,
)

def to_parquet(
self,
path: Union[str, os.PathLike[str], BinaryIO],
partition_cols: Optional[Sequence[str]] = None,
**kwargs,
) -> None:
"""Save chain to parquet file.
Parameters:
path : Path or a file-like binary object to save the file.
partition_cols : Column names by which to partition the dataset.
"""
_partition_cols = list(partition_cols) if partition_cols else None
return self.to_pandas().to_parquet(
path,
partition_cols=_partition_cols,
**kwargs,
)

@classmethod
def create_empty(
cls,
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/lib/test_datachain.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,34 @@ def test_from_parquet_partitioned(tmp_dir, catalog):
assert df1.equals(df)


def test_to_parquet(tmp_dir, catalog):
df = pd.DataFrame(DF_DATA)
dc = DataChain.from_pandas(df)

path = tmp_dir / "test.parquet"
dc.to_parquet(path)

assert path.is_file()
pd.testing.assert_frame_equal(pd.read_parquet(path), df)


def test_to_parquet_partitioned(tmp_dir, catalog):
df = pd.DataFrame(DF_DATA)
dc = DataChain.from_pandas(df)

path = tmp_dir / "parquets"
dc.to_parquet(path, partition_cols=["first_name"])

assert set(path.iterdir()) == {
path / f"first_name={name}" for name in df["first_name"]
}
df1 = pd.read_parquet(path)
df1 = df1.reindex(columns=df.columns)
df1["first_name"] = df1["first_name"].astype("str")
df1 = df1.sort_values("first_name").reset_index(drop=True)
pd.testing.assert_frame_equal(df1, df)


@pytest.mark.parametrize("processes", [False, 2, True])
def test_parallel(processes, catalog):
prefix = "t & "
Expand Down

0 comments on commit 69597f5

Please sign in to comment.