Debian Codegraph @

dask/dataframe/io/utils.py

raw
1 from __future__ import annotations
2
3 import json
4 from typing import Protocol, runtime_checkable
5 from uuid import uuid4
6
7 import fsspec
8 import pandas as pd
9 from fsspec.implementations.local import LocalFileSystem
10 from packaging.version import Version
11
12 try:
13 import fsspec.parquet as fsspec_parquet
14 except ImportError:
15 fsspec_parquet = None
16
17
18 def _is_local_fs(fs):
19 """Check if an fsspec file-system is local"""
20 return fs and (
21 isinstance(fs, LocalFileSystem)
22 # Check wrapped pyarrow filesystem
23 or _is_local_fs_pyarrow(fs)
24 )
25
26
27 def _is_local_fs_pyarrow(fs):
28 """Check if a pyarrow-based file-system is local"""
29 if fs:
30 if hasattr(fs, "fs"):
31 # ArrowFSWrapper will have an "fs" attribute
32 return _is_local_fs_pyarrow(fs.fs)
33 elif hasattr(fs, "type_name"):
34 # pa.fs.LocalFileSystem will have "type_name" attribute
35 return fs.type_name == "local"
36 return False
37
38
39 def _get_pyarrow_dtypes(schema, categories, dtype_backend=None):
40 """Convert a pyarrow.Schema object to pandas dtype dict"""
41 if dtype_backend == "numpy_nullable":
42 from dask.dataframe.io.parquet.arrow import PYARROW_NULLABLE_DTYPE_MAPPING
43
44 type_mapper = PYARROW_NULLABLE_DTYPE_MAPPING.get
45 else:
46 type_mapper = lambda t: t.to_pandas_dtype()
47
48 # Check for pandas metadata
49 has_pandas_metadata = schema.metadata is not None and b"pandas" in schema.metadata
50 if has_pandas_metadata:
51 pandas_metadata = json.loads(schema.metadata[b"pandas"].decode("utf8"))
52 pandas_metadata_dtypes = {
53 c.get("field_name", c.get("name", None)): c["numpy_type"]
54 for c in pandas_metadata.get("columns", [])
55 }
56 tz = {
57 c.get("field_name", c.get("name", None)): c["metadata"].get(
58 "timezone", None
59 )
60 for c in pandas_metadata.get("columns", [])
61 if c["pandas_type"] in ("datetime", "datetimetz") and c["metadata"]
62 }
63 else:
64 pandas_metadata_dtypes = {}
65
66 dtypes = {}
67 for i in range(len(schema)):
68 field = schema[i]
69
70 # Get numpy_dtype from pandas metadata if available
71 if field.name in pandas_metadata_dtypes:
72 if field.name in tz:
73 numpy_dtype = (
74 pd.Series([], dtype="M8[ns]").dt.tz_localize(tz[field.name]).dtype
75 )
76 else:
77 numpy_dtype = pandas_metadata_dtypes[field.name]
78 else:
79 try:
80 numpy_dtype = type_mapper(field.type)
81 except NotImplementedError:
82 continue # Skip this field (in case we aren't reading it anyway)
83
84 dtypes[field.name] = numpy_dtype
85
86 if categories:
87 for cat in categories:
88 dtypes[cat] = "category"
89
90 return dtypes
91
92
93 def _meta_from_dtypes(to_read_columns, file_dtypes, index_cols, column_index_names):
94 """Get the final metadata for the dask.dataframe
95
96 Parameters
97 ----------
98 to_read_columns : list
99 All the columns to end up with, including index names
100 file_dtypes : dict
101 Mapping from column name to dtype for every element
102 of ``to_read_columns``
103 index_cols : list
104 Subset of ``to_read_columns`` that should move to the
105 index
106 column_index_names : list
107 The values for df.columns.name for a MultiIndex in the
108 columns, or df.index.name for a regular Index in the columns
109
110 Returns
111 -------
112 meta : DataFrame
113 """
114 data = {
115 c: pd.Series([], dtype=file_dtypes.get(c, "int64")) for c in to_read_columns
116 }
117 indexes = [data.pop(c) for c in index_cols or []]
118 if len(indexes) == 0:
119 index = None
120 elif len(index_cols) == 1:
121 index = indexes[0]
122 # XXX: this means we can't roundtrip dataframes where the index names
123 # is actually __index_level_0__
124 if index_cols[0] != "__index_level_0__":
125 index.name = index_cols[0]
126 else:
127 index = pd.MultiIndex.from_arrays(indexes, names=index_cols)
128 df = pd.DataFrame(data, index=index)
129
130 if column_index_names:
131 df.columns.names = column_index_names
132 return df
133
134
135 def _guid():
136 """Simple utility function to get random hex string"""
137 return uuid4().hex
138
139
140 def _set_context(obj, stack):
141 """Helper function to place an object on a context stack"""
142 if stack is None:
143 return obj
144 return stack.enter_context(obj)
145
146
147 def _open_input_files(
148 paths,
149 fs=None,
150 context_stack=None,
151 open_file_func=None,
152 precache_options=None,
153 **kwargs,
154 ):
155 """Return a list of open-file objects given
156 a list of input-file paths.
157
158 WARNING: This utility is experimental, and is meant
159 for internal ``dask.dataframe`` use only.
160
161 Parameters
162 ----------
163 paths : list(str)
164 Remote or local path of the parquet file
165 fs : fsspec object, optional
166 File-system instance to use for file handling
167 context_stack : contextlib.ExitStack, Optional
168 Context manager to use for open files.
169 open_file_func : callable, optional
170 Callable function to use for file opening. If this argument
171 is specified, ``open_file_func(path, **kwargs)`` will be used
172 to open each file in ``paths``. Default is ``fs.open``.
173 precache_options : dict, optional
174 Dictionary of key-word arguments to use for precaching.
175 If ``precache_options`` contains ``{"method": "parquet"}``,
176 ``fsspec.parquet.open_parquet_file`` will be used for remote
177 storage.
178 **kwargs :
179 Key-word arguments to pass to the appropriate open function
180 """
181 # Use call-back function if specified
182 if open_file_func is not None:
183 return [
184 _set_context(open_file_func(path, **kwargs), context_stack)
185 for path in paths
186 ]
187
188 # Check if we are using `fsspec.parquet`.
189 # In the future, fsspec should be able to handle
190 # `{"method": "parquet"}`. However, for now we
191 # will redirect to `open_parquet_file` manually
192 precache_options = (precache_options or {}).copy()
193 precache = precache_options.pop("method", None)
194 if (
195 precache == "parquet"
196 and fs is not None
197 and not _is_local_fs(fs)
198 and Version(fsspec.__version__) > Version("2021.11.0")
199 ):
200 kwargs.update(precache_options)
201 row_groups = kwargs.pop("row_groups", None) or ([None] * len(paths))
202 cache_type = kwargs.pop("cache_type", "parts")
203 if cache_type != "parts":
204 raise ValueError(
205 f"'parts' `cache_type` required for 'parquet' precaching,"
206 f" got {cache_type}."
207 )
208 return [
209 _set_context(
210 fsspec_parquet.open_parquet_file(
211 path,
212 fs=fs,
213 row_groups=rgs,
214 **kwargs,
215 ),
216 context_stack,
217 )
218 for path, rgs in zip(paths, row_groups)
219 ]
220 elif fs is not None:
221 return [_set_context(fs.open(path, **kwargs), context_stack) for path in paths]
222 return [_set_context(open(path, **kwargs), context_stack) for path in paths]
223
224
225 @runtime_checkable
226 class DataFrameIOFunction(Protocol):
227 """DataFrame IO function with projectable columns
228
229 Enables column projection in ``DataFrameIOLayer``.
230 """
231
232 @property
233 def columns(self):
234 """Return the current column projection"""
235 raise NotImplementedError
236
237 def project_columns(self, columns):
238 """Return a new DataFrameIOFunction object
239 with a new column projection
240 """
241 raise NotImplementedError
242
243 def __call__(self, *args, **kwargs):
244 """Return a new DataFrame partition"""
245 raise NotImplementedError
246
247
248 @runtime_checkable
249 class SupportsLock(Protocol):
250 def acquire(self) -> object: ...
251
252 def release(self) -> object: ...