Debian Codegraph @

bioframe/sandbox/parquet_io.py

raw
1 import pandas as pd
2
3
4 def to_parquet(
5 pieces,
6 outpath,
7 row_group_size=None,
8 compression="snappy",
9 use_dictionary=True,
10 version=2.0,
11 **kwargs,
12 ):
13 """
14 Save an iterable of dataframe chunks to a single Apache Parquet file. For
15 more info about Parquet, see https://arrow.apache.org/docs/python/parquet.html.
16
17 Parameters
18 ----------
19 pieces : DataFrame or iterable of DataFrame
20 Chunks to write
21 outpath : str
22 Path to output file
23 row_group_size : int
24 Number of rows per row group
25 compression : {'snappy', 'gzip', 'brotli', 'none'}, optional
26 Compression algorithm. Can be set on a per-column basis with a
27 dictionary of column names to compression lib.
28 use_dictionary : bool, optional
29 Use dictionary encoding. Can be set on a per-column basis with a list
30 of column names.
31
32 See also
33 --------
34 pyarrow.parquet.write_table
35 pyarrow.parquet.ParquetFile
36 fastparquet
37
38 """
39 try:
40 import pyarrow as pa
41 import pyarrow.parquet
42 except ImportError:
43 raise ImportError("Saving to parquet requires the `pyarrow` package") from None
44
45 if isinstance(pieces, pd.DataFrame):
46 pieces = (pieces,)
47
48 try:
49 for i, piece in enumerate(pieces):
50 table = pa.Table.from_pandas(piece, preserve_index=False)
51 if i == 0:
52 writer = pa.parquet.ParquetWriter(
53 outpath,
54 table.schema,
55 compression=compression,
56 use_dictionary=use_dictionary,
57 version=version,
58 **kwargs,
59 )
60 writer.write_table(table, row_group_size=row_group_size)
61 finally:
62 writer.close()
63
64
65 def read_parquet(filepath, columns=None, iterator=False, **kwargs):
66 """
67 Load DataFrames from Parquet files, optionally in pieces.
68
69 Parameters
70 ----------
71 filepath : str, pathlib.Path, pyarrow.NativeFile, or file-like object
72 Readable source. For passing bytes or buffer-like file containing a
73 Parquet file, use pyarorw.BufferReader
74 columns: list
75 If not None, only these columns will be read from the row groups. A
76 column name may be a prefix of a nested field, e.g. 'a' will select
77 'a.b', 'a.c', and 'a.d.e'
78 iterator : boolean, default False
79 Return an iterator object that yields row group DataFrames and
80 provides the ParquetFile interface.
81 use_threads : boolean, default True
82 Perform multi-threaded column reads
83 memory_map : boolean, default True
84 If the source is a file path, use a memory map to read file, which can
85 improve performance in some environments
86
87 Returns
88 -------
89 DataFrame or ParquetFileIterator
90
91 """
92 use_threads = kwargs.pop("use_threads", True)
93
94 if not iterator:
95 return pd.read_parquet(
96 filepath, columns=columns, use_threads=use_threads, **kwargs
97 )
98 else:
99 try:
100 from pyarrow.parquet import ParquetFile
101 except ImportError:
102 raise ImportError(
103 "Iterating over Parquet data requires the `pyarrow` package."
104 ) from None
105
106 class ParquetFileIterator(ParquetFile):
107 def __iter__(self):
108 return self
109
110 def __next__(self):
111 if not hasattr(self, "_rgid"):
112 self._rgid = 0
113 if self._rgid < self.num_row_groups:
114 rg = self.read_row_group(
115 self._rgid,
116 columns=columns,
117 use_threads=use_threads,
118 use_pandas_metadata=True,
119 )
120 self._rgid += 1
121 else:
122 raise StopIteration
123 return rg.to_pandas()
124
125 return ParquetFileIterator(filepath, **kwargs)