Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parquet metadata persistence of DataFrame.attrs #54346

Merged
merged 8 commits into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
12 changes: 12 additions & 0 deletions pandas/io/parquet.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
""" parquet compat """
from __future__ import annotations

import ast
import io
import json
import os
from typing import (
TYPE_CHECKING,
Expand Down Expand Up @@ -184,6 +186,11 @@ def write(

table = self.api.Table.from_pandas(df, **from_pandas_kwargs)

df_metadata = {"df.attrs": json.dumps(df.attrs)}
mroeschke marked this conversation as resolved.
Show resolved Hide resolved
existing_metadata = table.schema.metadata
merged_metadata = {**existing_metadata, **df_metadata}
table = table.replace_schema_metadata(merged_metadata)

path_or_handle, handles, filesystem = _get_path_or_handle(
path,
filesystem,
Expand Down Expand Up @@ -263,6 +270,11 @@ def read(

if manager == "array":
result = result._as_manager("array", copy=False)

if pa_table.schema.metadata:
if b"df.attrs" in pa_table.schema.metadata:
df_metadata = pa_table.schema.metadata[b"df.attrs"]
result.attrs = ast.literal_eval(df_metadata.decode("utf-8"))
mroeschke marked this conversation as resolved.
Show resolved Hide resolved
return result
finally:
if handles is not None:
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/io/test_parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,14 @@ def test_empty_columns(self, pa):
df = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name"))
check_round_trip(df, pa)

def test_df_attrs_persistence(self, tmp_path, pa):
path = tmp_path / "test_df_metadata.p"
df = pd.DataFrame(data={1: [1]})
df.attrs = {"test_attribute": 1}
df.to_parquet(path, engine=pa)
new_df = read_parquet(path, engine=pa)
assert new_df.attrs == df.attrs


class TestParquetFastParquet(Base):
def test_basic(self, fp, df_full):
Expand Down
Loading