-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
782 lines (671 loc) · 24.4 KB
/
utils.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
from __future__ import annotations
import math
import re
import sys
import textwrap
import traceback
from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from numbers import Number
from typing import Callable, TypeVar, overload
import numpy as np
import pandas as pd
from pandas.api.types import is_categorical_dtype, is_dtype_equal
from dask.base import get_scheduler, is_dask_collection
from dask.core import get_deps
from dask.dataframe import ( # noqa: F401 register pandas extension types
_dtypes,
methods,
)
from dask.dataframe._compat import PANDAS_GT_110, PANDAS_GT_120, tm # noqa: F401
from dask.dataframe.dispatch import ( # noqa : F401
make_meta,
make_meta_obj,
meta_nonempty,
)
from dask.dataframe.extensions import make_scalar
from dask.utils import (
asciitable,
is_dataframe_like,
is_index_like,
is_series_like,
typename,
)
meta_object_types: tuple[type, ...] = (pd.Series, pd.DataFrame, pd.Index, pd.MultiIndex)
try:
import scipy.sparse as sp
meta_object_types += (sp.spmatrix,)
except ImportError:
pass
def is_integer_na_dtype(t):
dtype = getattr(t, "dtype", t)
types = (
pd.Int8Dtype,
pd.Int16Dtype,
pd.Int32Dtype,
pd.Int64Dtype,
pd.UInt8Dtype,
pd.UInt16Dtype,
pd.UInt32Dtype,
pd.UInt64Dtype,
)
return isinstance(dtype, types)
def is_float_na_dtype(t):
if not PANDAS_GT_120:
return False
dtype = getattr(t, "dtype", t)
types = (
pd.Float32Dtype,
pd.Float64Dtype,
)
return isinstance(dtype, types)
def shard_df_on_index(df, divisions):
"""Shard a DataFrame by ranges on its index
Examples
--------
>>> df = pd.DataFrame({'a': [0, 10, 20, 30, 40], 'b': [5, 4 ,3, 2, 1]})
>>> df
a b
0 0 5
1 10 4
2 20 3
3 30 2
4 40 1
>>> shards = list(shard_df_on_index(df, [2, 4]))
>>> shards[0]
a b
0 0 5
1 10 4
>>> shards[1]
a b
2 20 3
3 30 2
>>> shards[2]
a b
4 40 1
>>> list(shard_df_on_index(df, []))[0] # empty case
a b
0 0 5
1 10 4
2 20 3
3 30 2
4 40 1
"""
if isinstance(divisions, Iterator):
divisions = list(divisions)
if not len(divisions):
yield df
else:
divisions = np.array(divisions)
df = df.sort_index()
index = df.index
if is_categorical_dtype(index):
index = index.as_ordered()
indices = index.searchsorted(divisions)
yield df.iloc[: indices[0]]
for i in range(len(indices) - 1):
yield df.iloc[indices[i] : indices[i + 1]]
yield df.iloc[indices[-1] :]
_META_TYPES = "meta : pd.DataFrame, pd.Series, dict, iterable, tuple, optional"
_META_DESCRIPTION = """\
An empty ``pd.DataFrame`` or ``pd.Series`` that matches the dtypes and
column names of the output. This metadata is necessary for many algorithms
in dask dataframe to work. For ease of use, some alternative inputs are
also available. Instead of a ``DataFrame``, a ``dict`` of ``{name: dtype}``
or iterable of ``(name, dtype)`` can be provided (note that the order of
the names should match the order of the columns). Instead of a series, a
tuple of ``(name, dtype)`` can be used. If not provided, dask will try to
infer the metadata. This may lead to unexpected results, so providing
``meta`` is recommended. For more information, see
``dask.dataframe.utils.make_meta``.
"""
T = TypeVar("T", bound=Callable)
@overload
def insert_meta_param_description(func: T) -> T:
...
@overload
def insert_meta_param_description(pad: int) -> Callable[[T], T]:
...
def insert_meta_param_description(*args, **kwargs):
"""Replace `$META` in docstring with param description.
If pad keyword is provided, will pad description by that number of
spaces (default is 8)."""
if not args:
return lambda f: insert_meta_param_description(f, **kwargs)
f = args[0]
indent = " " * kwargs.get("pad", 8)
body = textwrap.wrap(
_META_DESCRIPTION, initial_indent=indent, subsequent_indent=indent, width=78
)
descr = "{}\n{}".format(_META_TYPES, "\n".join(body))
if f.__doc__:
if "$META" in f.__doc__:
f.__doc__ = f.__doc__.replace("$META", descr)
else:
# Put it at the end of the parameters section
parameter_header = "Parameters\n%s----------" % indent[4:]
first, last = re.split("Parameters\\n[ ]*----------", f.__doc__)
parameters, rest = last.split("\n\n", 1)
f.__doc__ = "{}{}{}\n{}{}\n\n{}".format(
first, parameter_header, parameters, indent[4:], descr, rest
)
return f
@contextmanager
def raise_on_meta_error(funcname=None, udf=False):
"""Reraise errors in this block to show metadata inference failure.
Parameters
----------
funcname : str, optional
If provided, will be added to the error message to indicate the
name of the method that failed.
"""
try:
yield
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
tb = "".join(traceback.format_tb(exc_traceback))
msg = "Metadata inference failed{0}.\n\n"
if udf:
msg += (
"You have supplied a custom function and Dask is unable to \n"
"determine the type of output that that function returns. \n\n"
"To resolve this please provide a meta= keyword.\n"
"The docstring of the Dask function you ran should have more information.\n\n"
)
msg += (
"Original error is below:\n"
"------------------------\n"
"{1}\n\n"
"Traceback:\n"
"---------\n"
"{2}"
)
msg = msg.format(f" in `{funcname}`" if funcname else "", repr(e), tb)
raise ValueError(msg) from e
UNKNOWN_CATEGORIES = "__UNKNOWN_CATEGORIES__"
def has_known_categories(x):
"""Returns whether the categories in `x` are known.
Parameters
----------
x : Series or CategoricalIndex
"""
x = getattr(x, "_meta", x)
if is_series_like(x):
return UNKNOWN_CATEGORIES not in x.cat.categories
elif is_index_like(x) and hasattr(x, "categories"):
return UNKNOWN_CATEGORIES not in x.categories
raise TypeError("Expected Series or CategoricalIndex")
def strip_unknown_categories(x, just_drop_unknown=False):
"""Replace any unknown categoricals with empty categoricals.
Useful for preventing ``UNKNOWN_CATEGORIES`` from leaking into results.
"""
if isinstance(x, (pd.Series, pd.DataFrame)):
x = x.copy()
if isinstance(x, pd.DataFrame):
cat_mask = x.dtypes == "category"
if cat_mask.any():
cats = cat_mask[cat_mask].index
for c in cats:
if not has_known_categories(x[c]):
if just_drop_unknown:
x[c].cat.remove_categories(UNKNOWN_CATEGORIES, inplace=True)
else:
x[c] = x[c].cat.set_categories([])
elif isinstance(x, pd.Series):
if is_categorical_dtype(x.dtype) and not has_known_categories(x):
x = x.cat.set_categories([])
if isinstance(x.index, pd.CategoricalIndex) and not has_known_categories(
x.index
):
x.index = x.index.set_categories([])
elif isinstance(x, pd.CategoricalIndex) and not has_known_categories(x):
x = x.set_categories([])
return x
def clear_known_categories(x, cols=None, index=True):
"""Set categories to be unknown.
Parameters
----------
x : DataFrame, Series, Index
cols : iterable, optional
If x is a DataFrame, set only categoricals in these columns to unknown.
By default, all categorical columns are set to unknown categoricals
index : bool, optional
If True and x is a Series or DataFrame, set the clear known categories
in the index as well.
"""
if isinstance(x, (pd.Series, pd.DataFrame)):
x = x.copy()
if isinstance(x, pd.DataFrame):
mask = x.dtypes == "category"
if cols is None:
cols = mask[mask].index
elif not mask.loc[cols].all():
raise ValueError("Not all columns are categoricals")
for c in cols:
x[c] = x[c].cat.set_categories([UNKNOWN_CATEGORIES])
elif isinstance(x, pd.Series):
if is_categorical_dtype(x.dtype):
x = x.cat.set_categories([UNKNOWN_CATEGORIES])
if index and isinstance(x.index, pd.CategoricalIndex):
x.index = x.index.set_categories([UNKNOWN_CATEGORIES])
elif isinstance(x, pd.CategoricalIndex):
x = x.set_categories([UNKNOWN_CATEGORIES])
return x
def _empty_series(name, dtype, index=None):
if isinstance(dtype, str) and dtype == "category":
s = pd.Series(pd.Categorical([UNKNOWN_CATEGORIES]), name=name).iloc[:0]
if index is not None:
s.index = make_meta(index)
return s
return pd.Series([], dtype=dtype, name=name, index=index)
_simple_fake_mapping = {
"b": np.bool_(True),
"V": np.void(b" "),
"M": np.datetime64("1970-01-01"),
"m": np.timedelta64(1),
"S": np.str_("foo"),
"a": np.str_("foo"),
"U": np.unicode_("foo"),
"O": "foo",
}
def _scalar_from_dtype(dtype):
if dtype.kind in ("i", "f", "u"):
return dtype.type(1)
elif dtype.kind == "c":
return dtype.type(complex(1, 0))
elif dtype.kind in _simple_fake_mapping:
o = _simple_fake_mapping[dtype.kind]
return o.astype(dtype) if dtype.kind in ("m", "M") else o
else:
raise TypeError(f"Can't handle dtype: {dtype}")
def _nonempty_scalar(x):
if type(x) in make_scalar._lookup:
return make_scalar(x)
if np.isscalar(x):
dtype = x.dtype if hasattr(x, "dtype") else np.dtype(type(x))
return make_scalar(dtype)
raise TypeError(f"Can't handle meta of type '{typename(type(x))}'")
def check_meta(x, meta, funcname=None, numeric_equal=True):
"""Check that the dask metadata matches the result.
If metadata matches, ``x`` is passed through unchanged. A nice error is
raised if metadata doesn't match.
Parameters
----------
x : DataFrame, Series, or Index
meta : DataFrame, Series, or Index
The expected metadata that ``x`` should match
funcname : str, optional
The name of the function in which the metadata was specified. If
provided, the function name will be included in the error message to be
more helpful to users.
numeric_equal : bool, optionl
If True, integer and floating dtypes compare equal. This is useful due
to panda's implicit conversion of integer to floating upon encountering
missingness, which is hard to infer statically.
"""
eq_types = {"i", "f", "u"} if numeric_equal else set()
def equal_dtypes(a, b):
if is_categorical_dtype(a) != is_categorical_dtype(b):
return False
if isinstance(a, str) and a == "-" or isinstance(b, str) and b == "-":
return False
if is_categorical_dtype(a) and is_categorical_dtype(b):
if UNKNOWN_CATEGORIES in a.categories or UNKNOWN_CATEGORIES in b.categories:
return True
return a == b
return (a.kind in eq_types and b.kind in eq_types) or is_dtype_equal(a, b)
if not (
is_dataframe_like(meta) or is_series_like(meta) or is_index_like(meta)
) or is_dask_collection(meta):
raise TypeError(
"Expected partition to be DataFrame, Series, or "
"Index, got `%s`" % typename(type(meta))
)
# Notice, we use .__class__ as opposed to type() in order to support
# object proxies see <https://github.com/dask/dask/pull/6981>
if x.__class__ != meta.__class__:
errmsg = "Expected partition of type `{}` but got `{}`".format(
typename(type(meta)),
typename(type(x)),
)
elif is_dataframe_like(meta):
dtypes = pd.concat([x.dtypes, meta.dtypes], axis=1, sort=True)
bad_dtypes = [
(repr(col), a, b)
for col, a, b in dtypes.fillna("-").itertuples()
if not equal_dtypes(a, b)
]
if bad_dtypes:
errmsg = "Partition type: `{}`\n{}".format(
typename(type(meta)),
asciitable(["Column", "Found", "Expected"], bad_dtypes),
)
else:
check_matching_columns(meta, x)
return x
else:
if equal_dtypes(x.dtype, meta.dtype):
return x
errmsg = "Partition type: `{}`\n{}".format(
typename(type(meta)),
asciitable(["", "dtype"], [("Found", x.dtype), ("Expected", meta.dtype)]),
)
raise ValueError(
"Metadata mismatch found%s.\n\n"
"%s" % ((" in `%s`" % funcname if funcname else ""), errmsg)
)
def check_matching_columns(meta, actual):
# Need nan_to_num otherwise nan comparison gives False
if not np.array_equal(np.nan_to_num(meta.columns), np.nan_to_num(actual.columns)):
extra = methods.tolist(actual.columns.difference(meta.columns))
missing = methods.tolist(meta.columns.difference(actual.columns))
if extra or missing:
extra_info = f" Extra: {extra}\n Missing: {missing}"
else:
extra_info = "Order of columns does not match"
raise ValueError(
"The columns in the computed data do not match"
" the columns in the provided metadata\n"
f"{extra_info}"
)
def index_summary(idx, name=None):
"""Summarized representation of an Index."""
n = len(idx)
if name is None:
name = idx.__class__.__name__
if n:
head = idx[0]
tail = idx[-1]
summary = f", {head} to {tail}"
else:
summary = ""
return f"{name}: {n} entries{summary}"
###############################################################
# Testing
###############################################################
def _check_dask(dsk, check_names=True, check_dtypes=True, result=None, scheduler=None):
import dask.dataframe as dd
if hasattr(dsk, "__dask_graph__"):
graph = dsk.__dask_graph__()
if hasattr(graph, "validate"):
graph.validate()
if result is None:
result = dsk.compute(scheduler=scheduler)
if isinstance(dsk, dd.Index):
assert "Index" in type(result).__name__, type(result)
# assert type(dsk._meta) == type(result), type(dsk._meta)
if check_names:
assert dsk.name == result.name
assert dsk._meta.name == result.name
if isinstance(result, pd.MultiIndex):
assert result.names == dsk._meta.names
if check_dtypes:
assert_dask_dtypes(dsk, result)
elif isinstance(dsk, dd.Series):
assert "Series" in type(result).__name__, type(result)
assert type(dsk._meta) == type(result), type(dsk._meta)
if check_names:
assert dsk.name == result.name, (dsk.name, result.name)
assert dsk._meta.name == result.name
if check_dtypes:
assert_dask_dtypes(dsk, result)
_check_dask(
dsk.index,
check_names=check_names,
check_dtypes=check_dtypes,
result=result.index,
)
elif isinstance(dsk, dd.DataFrame):
assert "DataFrame" in type(result).__name__, type(result)
assert isinstance(dsk.columns, pd.Index), type(dsk.columns)
assert type(dsk._meta) == type(result), type(dsk._meta)
if check_names:
tm.assert_index_equal(dsk.columns, result.columns)
tm.assert_index_equal(dsk._meta.columns, result.columns)
if check_dtypes:
assert_dask_dtypes(dsk, result)
_check_dask(
dsk.index,
check_names=check_names,
check_dtypes=check_dtypes,
result=result.index,
)
elif isinstance(dsk, dd.core.Scalar):
assert np.isscalar(result) or isinstance(
result, (pd.Timestamp, pd.Timedelta)
)
if check_dtypes:
assert_dask_dtypes(dsk, result)
else:
msg = f"Unsupported dask instance {type(dsk)} found"
raise AssertionError(msg)
return result
return dsk
def _maybe_sort(a, check_index: bool):
# sort by value, then index
try:
if is_dataframe_like(a):
if set(a.index.names) & set(a.columns):
a.index.names = [
"-overlapped-index-name-%d" % i for i in range(len(a.index.names))
]
a = a.sort_values(by=methods.tolist(a.columns))
else:
a = a.sort_values()
except (TypeError, IndexError, ValueError):
pass
return a.sort_index() if check_index else a
def assert_eq(
a,
b,
check_names=True,
check_dtype=True,
check_divisions=True,
check_index=True,
sort_results=True,
scheduler="sync",
**kwargs,
):
if check_divisions:
assert_divisions(a, scheduler=scheduler)
assert_divisions(b, scheduler=scheduler)
if hasattr(a, "divisions") and hasattr(b, "divisions"):
at = type(np.asarray(a.divisions).tolist()[0]) # numpy to python
bt = type(np.asarray(b.divisions).tolist()[0]) # scalar conversion
assert at == bt, (at, bt)
assert_sane_keynames(a)
assert_sane_keynames(b)
a = _check_dask(
a, check_names=check_names, check_dtypes=check_dtype, scheduler=scheduler
)
b = _check_dask(
b, check_names=check_names, check_dtypes=check_dtype, scheduler=scheduler
)
if hasattr(a, "to_pandas"):
a = a.to_pandas()
if hasattr(b, "to_pandas"):
b = b.to_pandas()
if isinstance(a, (pd.DataFrame, pd.Series)) and sort_results:
a = _maybe_sort(a, check_index)
b = _maybe_sort(b, check_index)
if not check_index:
a = a.reset_index(drop=True)
b = b.reset_index(drop=True)
if isinstance(a, pd.DataFrame):
tm.assert_frame_equal(
a, b, check_names=check_names, check_dtype=check_dtype, **kwargs
)
elif isinstance(a, pd.Series):
tm.assert_series_equal(
a, b, check_names=check_names, check_dtype=check_dtype, **kwargs
)
elif isinstance(a, pd.Index):
tm.assert_index_equal(a, b, exact=check_dtype, **kwargs)
else:
if a == b:
return True
else:
if np.isnan(a):
assert np.isnan(b)
else:
assert np.allclose(a, b)
return True
def assert_dask_graph(dask, label):
if hasattr(dask, "dask"):
dask = dask.dask
assert isinstance(dask, Mapping)
for k in dask:
if isinstance(k, tuple):
k = k[0]
if k.startswith(label):
return True
raise AssertionError(f"given dask graph doesn't contain label: {label}")
def assert_divisions(ddf, scheduler=None):
if not hasattr(ddf, "divisions"):
return
assert isinstance(ddf.divisions, tuple)
if not getattr(ddf, "known_divisions", False):
return
def index(x):
if is_index_like(x):
return x
try:
return x.index.get_level_values(0)
except AttributeError:
return x.index
get = get_scheduler(scheduler=scheduler, collections=[type(ddf)])
results = get(ddf.dask, ddf.__dask_keys__())
for i, df in enumerate(results[:-1]):
if len(df):
assert index(df).min() >= ddf.divisions[i]
assert index(df).max() < ddf.divisions[i + 1]
if len(results[-1]):
assert index(results[-1]).min() >= ddf.divisions[-2]
assert index(results[-1]).max() <= ddf.divisions[-1]
def assert_sane_keynames(ddf):
if not hasattr(ddf, "dask"):
return
for k in ddf.dask.keys():
while isinstance(k, tuple):
k = k[0]
assert isinstance(k, (str, bytes))
assert len(k) < 100
assert " " not in k
assert k.split("-")[0].isidentifier(), k
def assert_dask_dtypes(ddf, res, numeric_equal=True):
"""Check that the dask metadata matches the result.
If `numeric_equal`, integer and floating dtypes compare equal. This is
useful due to the implicit conversion of integer to floating upon
encountering missingness, which is hard to infer statically."""
eq_type_sets = [{"O", "S", "U", "a"}] # treat object and strings alike
if numeric_equal:
eq_type_sets.append({"i", "f", "u"})
def eq_dtypes(a, b):
return any(
a.kind in eq_types and b.kind in eq_types for eq_types in eq_type_sets
) or (a == b)
if not is_dask_collection(res) and is_dataframe_like(res):
for a, b in pd.concat([ddf._meta.dtypes, res.dtypes], axis=1).itertuples(
index=False
):
assert eq_dtypes(a, b)
elif not is_dask_collection(res) and (is_index_like(res) or is_series_like(res)):
a = ddf._meta.dtype
b = res.dtype
assert eq_dtypes(a, b)
else:
if hasattr(ddf._meta, "dtype"):
a = ddf._meta.dtype
if not hasattr(res, "dtype"):
assert np.isscalar(res)
b = np.dtype(type(res))
else:
b = res.dtype
assert eq_dtypes(a, b)
else:
assert type(ddf._meta) == type(res)
def assert_max_deps(x, n, eq=True):
dependencies, dependents = get_deps(x.dask)
if eq:
assert max(map(len, dependencies.values())) == n
else:
assert max(map(len, dependencies.values())) <= n
def valid_divisions(divisions):
"""Are the provided divisions valid?
Examples
--------
>>> valid_divisions([1, 2, 3])
True
>>> valid_divisions([3, 2, 1])
False
>>> valid_divisions([1, 1, 1])
False
>>> valid_divisions([0, 1, 1])
True
>>> valid_divisions(123)
False
>>> valid_divisions([0, float('nan'), 1])
False
"""
if not isinstance(divisions, (tuple, list)):
return False
for i, x in enumerate(divisions[:-2]):
if x >= divisions[i + 1]:
return False
if isinstance(x, Number) and math.isnan(x):
return False
for x in divisions[-2:]:
if isinstance(x, Number) and math.isnan(x):
return False
if divisions[-2] > divisions[-1]:
return False
return True
def drop_by_shallow_copy(df, columns, errors="raise"):
"""Use shallow copy to drop columns in place"""
df2 = df.copy(deep=False)
if not pd.api.types.is_list_like(columns):
columns = [columns]
df2.drop(columns=columns, inplace=True, errors=errors)
return df2
class AttributeNotImplementedError(NotImplementedError, AttributeError):
"""NotImplementedError and AttributeError"""
def meta_frame_constructor(like):
"""Return a serial DataFrame constructor
Parameters
----------
like :
Any series-like, Index-like or dataframe-like object.
"""
if is_dask_collection(like):
try:
like = like._meta
except AttributeError:
raise TypeError(f"{type(like)} not supported by meta_frame_constructor")
if is_dataframe_like(like):
return like._constructor
elif is_series_like(like):
return like._constructor_expanddim
elif is_index_like(like):
return like.to_frame()._constructor
else:
raise TypeError(f"{type(like)} not supported by meta_frame_constructor")
def meta_series_constructor(like):
"""Return a serial Series constructor
Parameters
----------
like :
Any series-like, Index-like or dataframe-like object.
"""
if is_dask_collection(like):
try:
like = like._meta
except AttributeError:
raise TypeError(f"{type(like)} not supported by meta_series_constructor")
if is_dataframe_like(like):
return like._constructor_sliced
elif is_series_like(like):
return like._constructor
elif is_index_like(like):
return like.to_frame()._constructor_sliced
else:
raise TypeError(f"{type(like)} not supported by meta_series_constructor")