/
column.py
274 lines (225 loc) · 6.87 KB
/
column.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# -*- coding: utf-8 -*-
from typing import List, Optional, Union
import pandas as pd
from pandas_select import iterutils
from pandas_select.label import LabelSelector
Dtypes = Union[str, List[str], type, List[type]]
LEGACY_PANDAS = pd.__version__ < "1.0.0" # noqa: WPS609
class HasDtype(LabelSelector):
"""Select columns based on the column dtypes.
Parameters
----------
include, exclude: scalar or list-like
A selection of dtypes or strings to be included/excluded. At least one of
these parameters must be supplied.
Raises
------
ValueError
If both of ``include`` and ``exclude`` are empty;
if ``include`` and ``exclude`` have overlapping elements;
if any kind of string dtype is passed in.
Notes
-----
* To select all *numeric* types, use ``numpy.number``, ``'number'``
or `:class:`AllNumeric`.
* To select strings you must use the ``object``, ``string`` dtype if pandas
version > 1.0.0, or or :class:`AllStr`
* See the `numpy dtype hierarchy
<http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html>`__
* To select datetimes, use :class:`numpy.datetime64`, ``'datetime'`` or
``'datetime64'``.
* To select timedeltas, use :class:`numpy.timedelta64`, ``'timedelta'`` or
``'timedelta64'``.
* To select Pandas categorical dtypes, use ``'category'`` or :class:`AllCat`.
* To select Pandas datetimetz dtypes, use ``'datetimetz'``
or ``'datetime64[ns, tz]'``.
See Also
--------
:meth:`pandas.DataFrame.select_dtypes`: base implementation
AllBool, AllNumeric, AllNominal
Examples
--------
>>> df = pd.DataFrame({"a": [1, 2],
... "b": [True, False],
... "c": [1.0, 2.0]})
>>> df
a b c
0 1 True 1.0
1 2 False 2.0
>>> df[HasDtype("int")]
a
0 1
1 2
>>> import numpy as np
>>> df[HasDtype(include=np.number, exclude=["int"])]
c
0 1.0
1 2.0
"""
def __init__(
self,
include: Optional[Dtypes] = None,
exclude: Optional[Dtypes] = None,
) -> None:
super().__init__(axis="columns", level=None)
self.include = include and iterutils.to_set(include)
self.exclude = exclude and iterutils.to_set(exclude)
def __call__(self, df: pd.DataFrame) -> pd.Index:
df_row = df.iloc[:1]
return df_row.select_dtypes(self.include, self.exclude).columns
class AllNumeric(HasDtype):
"""
Select numeric columns.
See Also
--------
HasDtype
Examples
--------
>>> df = pd.DataFrame({"a": [1, 2],
... "b": [True, False],
... "c": [1.0, 2.0]})
>>> df
a b c
0 1 True 1.0
1 2 False 2.0
>>> df[AllNumeric()]
a c
0 1 1.0
1 2 2.0
"""
def __init__(self) -> None:
super().__init__("number")
class AllBool(HasDtype):
"""Select boolean columns.
See Also
--------
HasDtype
Examples
--------
>>> df = pd.DataFrame({"a": [1, 2],
... "b": [True, False],
... "c": [1.0, 2.0]})
>>> df
a b c
0 1 True 1.0
1 2 False 2.0
>>> df[AllBool()]
b
0 True
1 False
"""
def __init__(self) -> None:
super().__init__("bool")
class AllCat(HasDtype):
"""Select categorical columns.
Parameters
----------
ordered: default None
Whether to filter ordered categorical, `None` to select all categorical columns.
See Also
--------
HasDtype, AllNominal
Examples
--------
>>> df = pd.DataFrame({"i": [1, 2],
... "cat": pd.Categorical(["a", "b"], ordered=False),
... "ordered_cat": pd.Categorical(["a", "b"], ordered=True)})
>>> df
i cat ordered_cat
0 1 a a
1 2 b b
>>> df[AllCat()]
cat ordered_cat
0 a a
1 b b
>>> df[AllCat(ordered=True)]
ordered_cat
0 a
1 b
"""
def __init__(self, *, ordered: Optional[bool] = None) -> None:
super().__init__("category")
self.ordered = ordered
def __call__(self, df: pd.DataFrame) -> pd.Index:
cols = super().__call__(df)
if self.ordered is not None:
drop_cols = [col for col in cols if df[col].cat.ordered != self.ordered]
cols = cols.drop(drop_cols)
return cols
def _get_str_dtypes(strict: bool) -> List[str]:
if strict:
if LEGACY_PANDAS:
raise ValueError("strict=True is incompatible with pandas < 1.0.0")
return ["string"]
return ["object"] if LEGACY_PANDAS else ["string", "object"]
class AllStr(HasDtype):
"""Select columns with dtype ``object``, and ``string`` if pandas version >= 1.0.0.
Parameters
----------
strict: default False
If True, filter out `object` dtypes.
Raises
------
ValueError
If pandas version < 1.0.0 and ``strict = True``
Notes
-----
Be aware that ``strict=False``, the default, will select **all** `object`
dtype columns. Columns with mixed types are stored with the `object` dtype!
See Also
--------
HasDtype, AllNominal
Examples
--------
>>> df = pd.DataFrame({"i": [1, 2],
... "o": ["a", 2],
... "obj_str": ["a", "b"],
... "str": ["a", "b"]})
>>> try:
... df = df.astype({"obj_str": "object", "str": "string"})
... except TypeError: # pandas.__version__ < '1.0.0'
... df = df.astype({"obj_str": "object", "str": "object"})
>>> df
i o obj_str str
0 1 a a a
1 2 2 b b
>>> df[AllStr()]
o obj_str str
0 a a a
1 2 b b
>>> pd.__version__ >= '1.0.0'
True
>>> df[AllStr(strict=True)]
str
0 a
1 b
"""
def __init__(self, *, strict: bool = False):
self.strict = strict
super().__init__(_get_str_dtypes(self.strict))
class AllNominal(HasDtype):
"""Select nominal columns.
Columns with the following dtypes are considered nominal: ``category``, ``object``,
and ``string`` if pandas version >= 1.0.0.
See Also
--------
HasDtype, AllCat, AllStr
Examples
--------
>>> df = pd.DataFrame({"a": [1, 2],
... "b": ["a", "b"],
... "c": ["a", "b"]})
>>> df = df.astype({"a": "int", "b": "object", "c": "category"})
>>> df
a b c
0 1 a a
1 2 b b
>>> df[AllNominal()]
b c
0 a a
1 b b
"""
def __init__(self, *, strict: bool = False) -> None:
self.strict = strict
dtypes = ["category", *_get_str_dtypes(strict)]
super().__init__(dtypes)