22from __future__ import annotations
33
44import io
5+ import json
56import os
67from typing import (
78 Any ,
@@ -154,6 +155,32 @@ def __init__(self):
154155
155156 self .api = pyarrow
156157
158+ @staticmethod
159+ def _write_attrs (table , df : DataFrame ):
160+ schema_metadata = table .schema .metadata or {}
161+ pandas_metadata = json .loads (schema_metadata .get (b"pandas" , "{}" ))
162+ column_attrs = {}
163+ for col in df .columns :
164+ attrs = df [col ].attrs
165+ if not attrs or not isinstance (col , str ):
166+ continue
167+ column_attrs [col ] = attrs
168+ pandas_metadata .update (
169+ attrs = df .attrs ,
170+ column_attrs = column_attrs ,
171+ )
172+ schema_metadata [b"pandas" ] = json .dumps (pandas_metadata )
173+ return table .replace_schema_metadata (schema_metadata )
174+
175+ @staticmethod
176+ def _read_attrs (table , df : DataFrame ):
177+ schema_metadata = table .schema .metadata or {}
178+ pandas_metadata = json .loads (schema_metadata .get (b"pandas" , "{}" ))
179+ df .attrs = pandas_metadata .get ("attrs" , {})
180+ col_attrs = pandas_metadata .get ("column_attrs" , {})
181+ for col , attrs in col_attrs .items ():
182+ df [col ].attrs = attrs
183+
157184 def write (
158185 self ,
159186 df : DataFrame ,
@@ -171,6 +198,7 @@ def write(
171198 from_pandas_kwargs ["preserve_index" ] = index
172199
173200 table = self .api .Table .from_pandas (df , ** from_pandas_kwargs )
201+ table = self ._write_attrs (table , df )
174202
175203 path_or_handle , handles , kwargs ["filesystem" ] = _get_path_or_handle (
176204 path ,
@@ -242,9 +270,11 @@ def read(
242270 mode = "rb" ,
243271 )
244272 try :
245- result = self .api .parquet .read_table (
273+ table = self .api .parquet .read_table (
246274 path_or_handle , columns = columns , ** kwargs
247- ).to_pandas (** to_pandas_kwargs )
275+ )
276+ result = table .to_pandas (** to_pandas_kwargs )
277+ self ._read_attrs (table , result )
248278 if manager == "array" :
249279 result = result ._as_manager ("array" , copy = False )
250280 return result
0 commit comments