Debian Codegraph @

dask/dataframe/_pyarrow.py

raw
1 from __future__ import annotations
2
3 from functools import partial
4
5 import pandas as pd
6 from packaging.version import Version
7
8 from dask._compatibility import import_optional_dependency
9 from dask.dataframe.utils import is_dataframe_like, is_index_like, is_series_like
10
11 try:
12 pa = import_optional_dependency("pyarrow")
13 except ImportError:
14 pa = None
15
16
17 def is_pyarrow_string_dtype(dtype):
18 """Is the input dtype a pyarrow string?"""
19 if pa is None:
20 return False
21 return dtype in (pd.StringDtype("pyarrow"), pd.ArrowDtype(pa.string()))
22
23
24 def is_object_string_dtype(dtype):
25 """Determine if input is a non-pyarrow string dtype"""
26 # in pandas < 2.0, is_string_dtype(DecimalDtype()) returns True
27 return (
28 pd.api.types.is_string_dtype(dtype)
29 and not is_pyarrow_string_dtype(dtype)
30 and not pd.api.types.is_dtype_equal(dtype, "decimal")
31 )
32
33
34 def is_pyarrow_string_index(x):
35 if isinstance(x, pd.MultiIndex):
36 return any(is_pyarrow_string_index(level) for level in x.levels)
37 return isinstance(x, pd.Index) and is_pyarrow_string_dtype(x.dtype)
38
39
40 def is_object_string_index(x):
41 if isinstance(x, pd.MultiIndex):
42 return any(is_object_string_index(level) for level in x.levels)
43 return isinstance(x, pd.Index) and is_object_string_dtype(x.dtype)
44
45
46 def is_object_string_series(x):
47 return isinstance(x, pd.Series) and (
48 is_object_string_dtype(x.dtype) or is_object_string_index(x.index)
49 )
50
51
52 def is_object_string_dataframe(x):
53 return isinstance(x, pd.DataFrame) and (
54 any(is_object_string_series(s) for _, s in x.items())
55 or is_object_string_index(x.index)
56 )
57
58
59 def _to_string_dtype(df, dtype_check, index_check, string_dtype):
60 if not (is_dataframe_like(df) or is_series_like(df) or is_index_like(df)):
61 return df
62
63 # Guards against importing `pyarrow` at the module level (where it may not be installed)
64 if string_dtype == "pyarrow":
65 string_dtype = pd.StringDtype("pyarrow")
66
67 # Possibly convert DataFrame/Series/Index to `string[pyarrow]`
68 if is_dataframe_like(df):
69 dtypes = {
70 col: string_dtype for col, dtype in df.dtypes.items() if dtype_check(dtype)
71 }
72 if dtypes:
73 df = df.astype(dtypes)
74 elif dtype_check(df.dtype):
75 dtypes = string_dtype
76 df = df.copy().astype(dtypes)
77
78 # Convert DataFrame/Series index too
79 if (is_dataframe_like(df) or is_series_like(df)) and index_check(df.index):
80 if isinstance(df.index, pd.MultiIndex):
81 levels = {
82 i: level.astype(string_dtype)
83 for i, level in enumerate(df.index.levels)
84 if dtype_check(level.dtype)
85 }
86 # set verify_integrity=False to preserve index codes
87 df.index = df.index.set_levels(
88 levels.values(), level=levels.keys(), verify_integrity=False
89 )
90 else:
91 df.index = df.index.astype(string_dtype)
92 return df
93
94
95 to_pyarrow_string = partial(
96 _to_string_dtype,
97 dtype_check=is_object_string_dtype,
98 index_check=is_object_string_index,
99 string_dtype="pyarrow",
100 )
101 to_object_string = partial(
102 _to_string_dtype,
103 dtype_check=is_pyarrow_string_dtype,
104 index_check=is_pyarrow_string_index,
105 string_dtype=object,
106 )
107
108
109 def check_pyarrow_string_supported():
110 """Make sure we have all the required versions"""
111 if pa is None or Version(pa.__version__) < Version("12.0.0"):
112 raise RuntimeError(
113 "Using dask's `dataframe.convert-string` configuration "
114 "option requires `pyarrow>=12` to be installed."
115 )