-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy path__init__.py
352 lines (316 loc) · 14.6 KB
/
__init__.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
from __future__ import annotations
from janitor.utils import import_message
from .clean_names import _clean_column_names, _clean_expr_names
try:
import polars as pl
except ImportError:
import_message(
submodule="polars",
package="polars",
conda_channel="conda-forge",
pip_install=True,
)
@pl.api.register_dataframe_namespace("janitor")
class PolarsFrame:
def __init__(self, df: pl.DataFrame) -> pl.DataFrame:
self._df = df
def clean_names(
self,
strip_underscores: str | bool = None,
case_type: str = "lower",
remove_special: bool = False,
strip_accents: bool = False,
truncate_limit: int = None,
) -> pl.DataFrame:
"""
Clean the column names in a polars DataFrame.
Examples:
>>> import polars as pl
>>> import janitor.polars
>>> df = pl.DataFrame(
... {
... "Aloha": range(3),
... "Bell Chart": range(3),
... "Animals@#$%^": range(3)
... }
... )
>>> df
shape: (3, 3)
┌───────┬────────────┬──────────────┐
│ Aloha ┆ Bell Chart ┆ Animals@#$%^ │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═══════╪════════════╪══════════════╡
│ 0 ┆ 0 ┆ 0 │
│ 1 ┆ 1 ┆ 1 │
│ 2 ┆ 2 ┆ 2 │
└───────┴────────────┴──────────────┘
>>> df.janitor.clean_names(remove_special=True)
shape: (3, 3)
┌───────┬────────────┬─────────┐
│ aloha ┆ bell_chart ┆ animals │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═══════╪════════════╪═════════╡
│ 0 ┆ 0 ┆ 0 │
│ 1 ┆ 1 ┆ 1 │
│ 2 ┆ 2 ┆ 2 │
└───────┴────────────┴─────────┘
!!! info "New in version 0.28.0"
Args:
strip_underscores: Removes the outer underscores from all
column names. Default None keeps outer underscores. Values can be
either 'left', 'right' or 'both' or the respective shorthand 'l',
'r' and True.
case_type: Whether to make the column names lower or uppercase.
Current case may be preserved with 'preserve',
while snake case conversion (from CamelCase or camelCase only)
can be turned on using "snake".
Default 'lower' makes all characters lowercase.
remove_special: Remove special characters from the column names.
Only letters, numbers and underscores are preserved.
strip_accents: Whether or not to remove accents from
the labels.
truncate_limit: Truncates formatted column names to
the specified length. Default None does not truncate.
Returns:
A polars DataFrame.
""" # noqa: E501
return self._df.rename(
lambda col: _clean_column_names(
obj=col,
strip_accents=strip_accents,
strip_underscores=strip_underscores,
case_type=case_type,
remove_special=remove_special,
truncate_limit=truncate_limit,
)
)
@pl.api.register_lazyframe_namespace("janitor")
class PolarsLazyFrame:
def __init__(self, df: pl.LazyFrame) -> pl.LazyFrame:
self._df = df
def clean_names(
self,
strip_underscores: str | bool = None,
case_type: str = "lower",
remove_special: bool = False,
strip_accents: bool = False,
truncate_limit: int = None,
) -> pl.LazyFrame:
"""
Clean the column names in a polars LazyFrame.
Examples:
>>> import polars as pl
>>> import janitor.polars
>>> df = pl.LazyFrame(
... {
... "Aloha": range(3),
... "Bell Chart": range(3),
... "Animals@#$%^": range(3)
... }
... )
>>> df.collect()
shape: (3, 3)
┌───────┬────────────┬──────────────┐
│ Aloha ┆ Bell Chart ┆ Animals@#$%^ │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═══════╪════════════╪══════════════╡
│ 0 ┆ 0 ┆ 0 │
│ 1 ┆ 1 ┆ 1 │
│ 2 ┆ 2 ┆ 2 │
└───────┴────────────┴──────────────┘
>>> df.janitor.clean_names(remove_special=True).collect()
shape: (3, 3)
┌───────┬────────────┬─────────┐
│ aloha ┆ bell_chart ┆ animals │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═══════╪════════════╪═════════╡
│ 0 ┆ 0 ┆ 0 │
│ 1 ┆ 1 ┆ 1 │
│ 2 ┆ 2 ┆ 2 │
└───────┴────────────┴─────────┘
!!! info "New in version 0.28.0"
Args:
strip_underscores: Removes the outer underscores from all
column names. Default None keeps outer underscores. Values can be
either 'left', 'right' or 'both' or the respective shorthand 'l',
'r' and True.
case_type: Whether to make the column names lower or uppercase.
Current case may be preserved with 'preserve',
while snake case conversion (from CamelCase or camelCase only)
can be turned on using "snake".
Default 'lower' makes all characters lowercase.
remove_special: Remove special characters from the column names.
Only letters, numbers and underscores are preserved.
strip_accents: Whether or not to remove accents from
the labels.
truncate_limit: Truncates formatted column names to
the specified length. Default None does not truncate.
Returns:
A polars LazyFrame.
""" # noqa: E501
return self._df.rename(
lambda col: _clean_column_names(
obj=col,
strip_accents=strip_accents,
strip_underscores=strip_underscores,
case_type=case_type,
remove_special=remove_special,
truncate_limit=truncate_limit,
)
)
@pl.api.register_expr_namespace("janitor")
class PolarsExpr:
def __init__(self, expr: pl.Expr) -> pl.Expr:
self._expr = expr
def clean_names(
self,
strip_underscores: str | bool = None,
case_type: str = "lower",
remove_special: bool = False,
strip_accents: bool = False,
enforce_string: bool = False,
truncate_limit: int = None,
) -> pl.Expr:
"""
Clean the labels in a polars Expression.
Examples:
>>> import polars as pl
>>> import janitor.polars
>>> df = pl.DataFrame({"raw": ["Abçdê fgí j"]})
>>> df
shape: (1, 1)
┌─────────────┐
│ raw │
│ --- │
│ str │
╞═════════════╡
│ Abçdê fgí j │
└─────────────┘
Clean the column values:
>>> df.with_columns(pl.col("raw").janitor.clean_names(strip_accents=True))
shape: (1, 1)
┌─────────────┐
│ raw │
│ --- │
│ str │
╞═════════════╡
│ abcde_fgi_j │
└─────────────┘
!!! info "New in version 0.28.0"
Args:
strip_underscores: Removes the outer underscores
from all labels in the expression.
Default None keeps outer underscores.
Values can be either 'left', 'right'
or 'both' or the respective shorthand 'l',
'r' and True.
case_type: Whether to make the labels in the expression lower or uppercase.
Current case may be preserved with 'preserve',
while snake case conversion (from CamelCase or camelCase only)
can be turned on using "snake".
Default 'lower' makes all characters lowercase.
remove_special: Remove special characters from the values in the expression.
Only letters, numbers and underscores are preserved.
strip_accents: Whether or not to remove accents from
the expression.
enforce_string: Whether or not to cast the expression to a string type.
truncate_limit: Truncates formatted labels in the expression to
the specified length. Default None does not truncate.
Returns:
A polars Expression.
"""
return _clean_expr_names(
obj=self._expr,
strip_accents=strip_accents,
strip_underscores=strip_underscores,
case_type=case_type,
remove_special=remove_special,
enforce_string=enforce_string,
truncate_limit=truncate_limit,
)
def convert_excel_date(self) -> pl.Expr:
"""
Convert Excel's serial date format into Python datetime format.
Inspiration is from
[Stack Overflow](https://stackoverflow.com/questions/38454403/convert-excel-style-date-with-pandas).
Examples:
>>> import polars as pl
>>> import janitor.polars
>>> df = pl.DataFrame({"date": [39690, 39690, 37118]})
>>> df
shape: (3, 1)
┌───────┐
│ date │
│ --- │
│ i64 │
╞═══════╡
│ 39690 │
│ 39690 │
│ 37118 │
└───────┘
>>> expression = pl.col('date').janitor.convert_excel_date().alias('date_')
>>> df.with_columns(expression)
shape: (3, 2)
┌───────┬────────────┐
│ date ┆ date_ │
│ --- ┆ --- │
│ i64 ┆ date │
╞═══════╪════════════╡
│ 39690 ┆ 2008-08-30 │
│ 39690 ┆ 2008-08-30 │
│ 37118 ┆ 2001-08-15 │
└───────┴────────────┘
!!! info "New in version 0.28.0"
Returns:
A polars Expression.
""" # noqa: E501
expression = pl.duration(days=self._expr)
expression += pl.date(year=1899, month=12, day=30)
return expression
def convert_matlab_date(self) -> pl.Expr:
"""
Convert Matlab's serial date number into Python datetime format.
Implementation is from
[Stack Overflow](https://stackoverflow.com/questions/13965740/converting-matlabs-datenum-format-to-python).
Examples:
>>> import polars as pl
>>> import janitor.polars
>>> df = pl.DataFrame({"date": [737125.0, 737124.815863, 737124.4985, 737124]})
>>> df
shape: (4, 1)
┌───────────────┐
│ date │
│ --- │
│ f64 │
╞═══════════════╡
│ 737125.0 │
│ 737124.815863 │
│ 737124.4985 │
│ 737124.0 │
└───────────────┘
>>> expression = pl.col('date').janitor.convert_matlab_date().alias('date_')
>>> df.with_columns(expression)
shape: (4, 2)
┌───────────────┬─────────────────────────┐
│ date ┆ date_ │
│ --- ┆ --- │
│ f64 ┆ datetime[μs] │
╞═══════════════╪═════════════════════════╡
│ 737125.0 ┆ 2018-03-06 00:00:00 │
│ 737124.815863 ┆ 2018-03-05 19:34:50.563 │
│ 737124.4985 ┆ 2018-03-05 11:57:50.399 │
│ 737124.0 ┆ 2018-03-05 00:00:00 │
└───────────────┴─────────────────────────┘
!!! info "New in version 0.28.0"
Returns:
A polars Expression.
""" # noqa: E501
# https://stackoverflow.com/questions/13965740/converting-matlabs-datenum-format-to-python
expression = self._expr.sub(719529).mul(86_400_000)
expression = pl.duration(milliseconds=expression)
expression += pl.datetime(year=1970, month=1, day=1)
return expression