Debian Codegraph @

dask/bag/core.py

raw ◀ ▶
1 Debian patch touch this file
1 from __future__ import annotations
2
3 import io
4 import itertools
5 import math
6 import operator
7 import uuid
8 import warnings
9 from collections import defaultdict
10 from collections.abc import Iterable, Iterator, Sequence
11 from functools import partial, reduce, wraps
12 from random import Random
13 from urllib.request import urlopen
14
15 import tlz as toolz
16 from fsspec.core import open_files
17 from tlz import (
18 accumulate,
19 compose,
20 count,
21 curry,
22 first,
23 frequencies,
24 groupby,
25 join,
26 merge,
27 merge_with,
28 partition_all,
29 peek,
30 pluck,
31 reduceby,
32 remove,
33 second,
34 take,
35 topk,
36 unique,
37 valmap,
38 )
39
40 from dask import config
41 from dask._task_spec import (
42 GraphNode,
43 List,
44 Task,
45 TaskRef,
46 _execute_subgraph,
47 convert_legacy_graph,
48 cull,
49 fuse_linear_task_spec,
50 )
51 from dask.bag import chunk
52 from dask.bag.avro import to_avro
53 from dask.base import (
54 DaskMethodsMixin,
55 dont_optimize,
56 named_schedulers,
57 replace_name_in_key,
58 tokenize,
59 )
60 from dask.blockwise import _blockwise_unpack_collections_task_spec, blockwise
61 from dask.context import globalmethod
62 from dask.core import flatten, istask, quote
63 from dask.delayed import Delayed
64 from dask.highlevelgraph import HighLevelGraph
65 from dask.sizeof import sizeof
66 from dask.typing import Graph, NestedKeys, no_default
67 from dask.utils import (
68 apply,
69 digit,
70 ensure_bytes,
71 ensure_unicode,
72 funcname,
73 get_default_shuffle_method,
74 insert,
75 iter_chunks,
76 key_split,
77 parse_bytes,
78 system_encoding,
79 takes_multiple_arguments,
80 )
81
82 DEFAULT_GET = named_schedulers.get("processes", named_schedulers["sync"])
83
84 no_result = type(
85 "no_result", (object,), {"__slots__": (), "__reduce__": lambda self: "no_result"}
86 )
87
88
89 def lazify_task(task, start=True):
90 """
91 Given a task, remove unnecessary calls to ``list`` and ``reify``.
92
93 This traverses tasks and small lists. We choose not to traverse down lists
94 of size >= 50 because it is unlikely that sequences this long contain other
95 sequences in practice.
96
97 Examples
98 --------
99 >>> def inc(x):
100 ... return x + 1
101 >>> task = (sum, (list, (map, inc, [1, 2, 3])))
102 >>> lazify_task(task) # doctest: +ELLIPSIS
103 (<built-in function sum>, (<class 'map'>, <function inc at ...>, [1, 2, 3]))
104 """
105
106 if isinstance(task, GraphNode):
107 if isinstance(task, List) and len(task.args) < 50:
108 return List(*[lazify_task(arg, False) for arg in task.args])
109 if not isinstance(task, Task):
110 return task
111 if not start and task.func in (list, reify) and isinstance(task.args[0], Task):
112 assert len(task.args) == 1
113 task = task.args[0]
114 if task.func is _execute_subgraph:
115 subgraph = task.args[0]
116 outkey = task.args[1]
117 # If there is a reify at the output of the subgraph we don't want to act
118 final_task = lazify_task(subgraph[outkey], True)
119 subgraph = {
120 k: lazify_task(v, False) for k, v in subgraph.items() if k != outkey
121 }
122 subgraph[outkey] = final_task
123 return Task(
124 task.key,
125 _execute_subgraph,
126 subgraph,
127 outkey,
128 *task.args[2:],
129 **task.kwargs,
130 )
131 return Task(
132 task.key,
133 task.func,
134 *[lazify_task(arg, False) for arg in task.args],
135 **task.kwargs,
136 )
137 else:
138 if type(task) is list and len(task) < 50:
139 return [lazify_task(arg, False) for arg in task]
140 if not istask(task):
141 return task
142 head, tail = task[0], task[1:]
143 if not start and head in (list, reify):
144 task = task[1]
145 return lazify_task(*tail, start=False)
146 else:
147 return (head,) + tuple(lazify_task(arg, False) for arg in tail)
148
149
150 def lazify(dsk):
151 """
152 Remove unnecessary calls to ``list`` in tasks.
153
154 See Also
155 --------
156 dask.bag.core.lazify_task
157 """
158 return valmap(lazify_task, dsk)
159
160
161 def optimize(dsk, keys, fuse_keys=None, **kwargs):
162 """Optimize a dask from a dask Bag."""
163 dsk = convert_legacy_graph(dsk)
164 keys = list(flatten(keys))
165 dsk2 = cull(dsk, keys)
166 dsk3 = fuse_linear_task_spec(dsk2, keys + (fuse_keys or []))
167 dsk4 = lazify(dsk3)
168 return dsk4
169
170
171 def _to_textfiles_chunk(data, lazy_file, last_endline):
172 with lazy_file as f:
173 if isinstance(f, io.TextIOWrapper):
174 endline = "\n"
175 ensure = ensure_unicode
176 else:
177 endline = b"\n"
178 ensure = ensure_bytes
179 started = False
180 for d in data:
181 if started:
182 f.write(endline)
183 else:
184 started = True
185 f.write(ensure(d))
186 if last_endline:
187 f.write(endline)
188
189
190 def to_textfiles(
191 b,
192 path,
193 name_function=None,
194 compression="infer",
195 encoding=system_encoding,
196 compute=True,
197 storage_options=None,
198 last_endline=False,
199 **kwargs,
200 ):
201 """Write dask Bag to disk, one filename per partition, one line per element.
202
203 **Paths**: This will create one file for each partition in your bag. You
204 can specify the filenames in a variety of ways.
205
206 Use a globstring
207
208 >>> b.to_textfiles('/path/to/data/*.json.gz') # doctest: +SKIP
209
210 The * will be replaced by the increasing sequence 1, 2, ...
211
212 ::
213
214 /path/to/data/0.json.gz
215 /path/to/data/1.json.gz
216
217 Use a globstring and a ``name_function=`` keyword argument. The
218 name_function function should expect an integer and produce a string.
219 Strings produced by name_function must preserve the order of their
220 respective partition indices.
221
222 >>> from datetime import date, timedelta
223 >>> def name(i):
224 ... return str(date(2015, 1, 1) + i * timedelta(days=1))
225
226 >>> name(0)
227 '2015-01-01'
228 >>> name(15)
229 '2015-01-16'
230
231 >>> b.to_textfiles('/path/to/data/*.json.gz', name_function=name) # doctest: +SKIP
232
233 ::
234
235 /path/to/data/2015-01-01.json.gz
236 /path/to/data/2015-01-02.json.gz
237 ...
238
239 You can also provide an explicit list of paths.
240
241 >>> paths = ['/path/to/data/alice.json.gz', '/path/to/data/bob.json.gz', ...] # doctest: +SKIP
242 >>> b.to_textfiles(paths) # doctest: +SKIP
243
244 **Compression**: Filenames with extensions corresponding to known
245 compression algorithms (gz, bz2) will be compressed accordingly.
246
247 **Bag Contents**: The bag calling ``to_textfiles`` must be a bag of
248 text strings. For example, a bag of dictionaries could be written to
249 JSON text files by mapping ``json.dumps`` on to the bag first, and
250 then calling ``to_textfiles`` :
251
252 >>> b_dict.map(json.dumps).to_textfiles("/path/to/data/*.json") # doctest: +SKIP
253
254 **Last endline**: By default the last line does not end with a newline
255 character. Pass ``last_endline=True`` to invert the default.
256 """
257 mode = "wb" if encoding is None else "wt"
258 files = open_files(
259 path,
260 compression=compression,
261 mode=mode,
262 encoding=encoding,
263 name_function=name_function,
264 num=b.npartitions,
265 **(storage_options or {}),
266 )
267
268 name = "to-textfiles-" + uuid.uuid4().hex
269 dsk = {
270 (name, i): (_to_textfiles_chunk, (b.name, i), f, last_endline)
271 for i, f in enumerate(files)
272 }
273 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[b])
274 out = type(b)(graph, name, b.npartitions)
275
276 if compute:
277 out.compute(**kwargs)
278 return [f.path for f in files]
279 else:
280 return out.to_delayed()
281
282
283 def finalize(results):
284 if not results:
285 return results
286 if isinstance(results, Iterator):
287 results = list(results)
288 if isinstance(results[0], Iterable) and not isinstance(results[0], str):
289 results = toolz.concat(results)
290 if isinstance(results, Iterator):
291 results = list(results)
292 return results
293
294
295 def finalize_item(results):
296 return results[0]
297
298
299 class StringAccessor:
300 """String processing functions
301
302 Examples
303 --------
304
305 >>> import dask.bag as db
306 >>> b = db.from_sequence(['Alice Smith', 'Bob Jones', 'Charlie Smith'])
307 >>> list(b.str.lower())
308 ['alice smith', 'bob jones', 'charlie smith']
309
310 >>> list(b.str.match('*Smith'))
311 ['Alice Smith', 'Charlie Smith']
312
313 >>> list(b.str.split(' '))
314 [['Alice', 'Smith'], ['Bob', 'Jones'], ['Charlie', 'Smith']]
315 """
316
317 def __init__(self, bag):
318 self._bag = bag
319
320 def __dir__(self):
321 return sorted(set(dir(type(self)) + dir(str)))
322
323 def _strmap(self, key, *args, **kwargs):
324 return self._bag.map(operator.methodcaller(key, *args, **kwargs))
325
326 def __getattr__(self, key):
327 try:
328 return object.__getattribute__(self, key)
329 except AttributeError:
330 if key in dir(str):
331 func = getattr(str, key)
332 return robust_wraps(func)(partial(self._strmap, key))
333 else:
334 raise
335
336 def match(self, pattern):
337 """Filter strings by those that match a pattern.
338
339 Examples
340 --------
341
342 >>> import dask.bag as db
343 >>> b = db.from_sequence(['Alice Smith', 'Bob Jones', 'Charlie Smith'])
344 >>> list(b.str.match('*Smith'))
345 ['Alice Smith', 'Charlie Smith']
346
347 See Also
348 --------
349 fnmatch.fnmatch
350 """
351 from fnmatch import fnmatch
352
353 return self._bag.filter(partial(fnmatch, pat=pattern))
354
355
356 def robust_wraps(wrapper):
357 """A weak version of wraps that only copies doc."""
358
359 def _(wrapped):
360 wrapped.__doc__ = wrapper.__doc__
361 return wrapped
362
363 return _
364
365
366 class Item(DaskMethodsMixin):
367 def __init__(self, dsk, key, layer=None):
368 self.dask = dsk
369 self.key = key
370 self.name = key
371
372 # NOTE: Layer only used by `Item.from_delayed`, to handle Delayed objects created by other collections.
373 # e.g.: Item.from_delayed(da.ones(1).to_delayed()[0])
374 # See Delayed.__init__
375 self._layer = layer or key
376 if isinstance(dsk, HighLevelGraph) and self._layer not in dsk.layers:
377 raise ValueError(
378 f"Layer {self._layer} not in the HighLevelGraph's layers: {list(dsk.layers)}"
379 )
380
381 def __dask_graph__(self) -> Graph:
382 return self.dask
383
384 def __dask_keys__(self) -> NestedKeys:
385 return [self.key]
386
387 def __dask_layers__(self) -> Sequence[str]:
388 return (self._layer,)
389
390 def __dask_tokenize__(self):
391 return self.key
392
393 __dask_optimize__ = globalmethod(optimize, key="bag_optimize", falsey=dont_optimize)
394 __dask_scheduler__ = staticmethod(DEFAULT_GET)
395
396 def __dask_postcompute__(self):
397 return finalize_item, ()
398
399 def __dask_postpersist__(self):
400 return self._rebuild, ()
401
402 def _rebuild(self, dsk, *, rename=None):
403 key = replace_name_in_key(self.key, rename) if rename else self.key
404 return Item(dsk, key)
405
406 @staticmethod
407 def from_delayed(value):
408 """Create bag item from a dask.delayed value.
409
410 See ``dask.bag.from_delayed`` for details
411 """
412 from dask.delayed import Delayed, delayed
413
414 if not isinstance(value, Delayed) and hasattr(value, "key"):
415 value = delayed(value)
416 assert isinstance(value, Delayed)
417 return Item(value.dask, value.key, layer=value.__dask_layers__()[0])
418
419 @property
420 def _args(self):
421 return (self.dask, self.key)
422
423 def __getstate__(self):
424 return self._args
425
426 def __setstate__(self, state):
427 self.dask, self.key = state
428
429 def apply(self, func):
430 name = "{}-{}".format(funcname(func), tokenize(self, func, "apply"))
431 dsk = {name: (func, self.key)}
432 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
433 return Item(graph, name)
434
435 __int__ = __float__ = __complex__ = __bool__ = DaskMethodsMixin.compute
436
437 def to_delayed(self, optimize_graph=True):
438 """Convert into a ``dask.delayed`` object.
439
440 Parameters
441 ----------
442 optimize_graph : bool, optional
443 If True [default], the graph is optimized before converting into
444 ``dask.delayed`` objects.
445 """
446 from dask.delayed import Delayed
447
448 dsk = self.__dask_graph__()
449 if optimize_graph:
450 dsk = self.__dask_optimize__(dsk, self.__dask_keys__())
451 return Delayed(self.key, dsk, layer=self._layer)
452
453
454 class Bag(DaskMethodsMixin):
455 """Parallel collection of Python objects
456
457 Examples
458 --------
459 Create Bag from sequence
460
461 >>> import dask.bag as db
462 >>> b = db.from_sequence(range(5))
463 >>> list(b.filter(lambda x: x % 2 == 0).map(lambda x: x * 10))
464 [0, 20, 40]
465
466 Create Bag from filename or globstring of filenames
467
468 >>> b = db.read_text('/path/to/mydata.*.json.gz').map(json.loads) # doctest: +SKIP
469
470 Create manually (expert use)
471
472 >>> dsk = {('x', 0): (range, 5),
473 ... ('x', 1): (range, 5),
474 ... ('x', 2): (range, 5)}
475 >>> b = db.Bag(dsk, 'x', npartitions=3)
476
477 >>> sorted(b.map(lambda x: x * 10))
478 [0, 0, 0, 10, 10, 10, 20, 20, 20, 30, 30, 30, 40, 40, 40]
479
480 >>> int(b.fold(lambda x, y: x + y))
481 30
482 """
483
484 def __init__(self, dsk: Graph, name: str, npartitions: int):
485 if not isinstance(dsk, HighLevelGraph):
486 dsk = HighLevelGraph.from_collections(name, dsk, dependencies=[])
487 self.dask = dsk
488 self.name = name
489 self.npartitions = npartitions
490
491 def __dask_graph__(self) -> Graph:
492 return self.dask
493
494 def __dask_keys__(self) -> NestedKeys:
495 return [(self.name, i) for i in range(self.npartitions)]
496
497 def __dask_layers__(self) -> Sequence[str]:
498 return (self.name,)
499
500 def __dask_tokenize__(self):
501 return self.name
502
503 __dask_optimize__ = globalmethod(optimize, key="bag_optimize", falsey=dont_optimize)
504 __dask_scheduler__ = staticmethod(DEFAULT_GET)
505
506 def __dask_postcompute__(self):
507 return finalize, ()
508
509 def __dask_postpersist__(self):
510 return self._rebuild, ()
511
512 def _rebuild(self, dsk, *, rename=None):
513 name = self.name
514 if rename:
515 name = rename.get(name, name)
516 return type(self)(dsk, name, self.npartitions)
517
518 def __str__(self):
519 return "dask.bag<%s, npartitions=%d>" % (key_split(self.name), self.npartitions)
520
521 __repr__ = __str__
522
523 str = property(fget=StringAccessor)
524
525 def map(self, func, *args, **kwargs):
526 """Apply a function elementwise across one or more bags.
527
528 Note that all ``Bag`` arguments must be partitioned identically.
529
530 Parameters
531 ----------
532 func : callable
533 *args, **kwargs : Bag, Item, or object
534 Extra arguments and keyword arguments to pass to ``func`` *after*
535 the calling bag instance. Non-Bag args/kwargs are broadcasted
536 across all calls to ``func``.
537
538 Notes
539 -----
540 For calls with multiple `Bag` arguments, corresponding partitions
541 should have the same length; if they do not, the call will error at
542 compute time.
543
544 Examples
545 --------
546 >>> import dask.bag as db
547 >>> b = db.from_sequence(range(5), npartitions=2)
548 >>> b2 = db.from_sequence(range(5, 10), npartitions=2)
549
550 Apply a function to all elements in a bag:
551
552 >>> b.map(lambda x: x + 1).compute()
553 [1, 2, 3, 4, 5]
554
555 Apply a function with arguments from multiple bags:
556
557 >>> from operator import add
558 >>> b.map(add, b2).compute()
559 [5, 7, 9, 11, 13]
560
561 Non-bag arguments are broadcast across all calls to the mapped
562 function:
563
564 >>> b.map(add, 1).compute()
565 [1, 2, 3, 4, 5]
566
567 Keyword arguments are also supported, and have the same semantics as
568 regular arguments:
569
570 >>> def myadd(x, y=0):
571 ... return x + y
572 >>> b.map(myadd, y=b2).compute()
573 [5, 7, 9, 11, 13]
574 >>> b.map(myadd, y=1).compute()
575 [1, 2, 3, 4, 5]
576
577 Both arguments and keyword arguments can also be instances of
578 ``dask.bag.Item``. Here we'll add the max value in the bag to each
579 element:
580
581 >>> b.map(myadd, b.max()).compute()
582 [4, 5, 6, 7, 8]
583 """
584 return bag_map(func, self, *args, **kwargs)
585
586 def starmap(self, func, **kwargs):
587 """Apply a function using argument tuples from the given bag.
588
589 This is similar to ``itertools.starmap``, except it also accepts
590 keyword arguments. In pseudocode, this is could be written as:
591
592 >>> def starmap(func, bag, **kwargs):
593 ... return (func(*args, **kwargs) for args in bag)
594
595 Parameters
596 ----------
597 func : callable
598 **kwargs : Item, Delayed, or object, optional
599 Extra keyword arguments to pass to ``func``. These can either be
600 normal objects, ``dask.bag.Item``, or ``dask.delayed.Delayed``.
601
602 Examples
603 --------
604 >>> import dask.bag as db
605 >>> data = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
606 >>> b = db.from_sequence(data, npartitions=2)
607
608 Apply a function to each argument tuple:
609
610 >>> from operator import add
611 >>> b.starmap(add).compute()
612 [3, 7, 11, 15, 19]
613
614 Apply a function to each argument tuple, with additional keyword
615 arguments:
616
617 >>> def myadd(x, y, z=0):
618 ... return x + y + z
619 >>> b.starmap(myadd, z=10).compute()
620 [13, 17, 21, 25, 29]
621
622 Keyword arguments can also be instances of ``dask.bag.Item`` or
623 ``dask.delayed.Delayed``:
624
625 >>> max_second = b.pluck(1).max()
626 >>> max_second.compute()
627 10
628 >>> b.starmap(myadd, z=max_second).compute()
629 [13, 17, 21, 25, 29]
630 """
631 name = "{}-{}".format(funcname(func), tokenize(self, func, "starmap", **kwargs))
632 dependencies = [self]
633 if kwargs:
634 kwargs, collections = unpack_scalar_dask_kwargs(kwargs)
635 dependencies.extend(collections)
636
637 dsk = {
638 (name, i): (reify, (starmap_chunk, func, (self.name, i), kwargs))
639 for i in range(self.npartitions)
640 }
641 graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
642 return type(self)(graph, name, self.npartitions)
643
644 @property
645 def _args(self):
646 return (self.dask, self.name, self.npartitions)
647
648 def __getstate__(self):
649 return self._args
650
651 def __setstate__(self, state):
652 self.dask, self.name, self.npartitions = state
653
654 def filter(self, predicate):
655 """Filter elements in collection by a predicate function.
656
657 >>> def iseven(x):
658 ... return x % 2 == 0
659
660 >>> import dask.bag as db
661 >>> b = db.from_sequence(range(5))
662 >>> list(b.filter(iseven))
663 [0, 2, 4]
664 """
665 name = f"filter-{funcname(predicate)}-{tokenize(self, predicate)}"
666 dsk = {
667 (name, i): (reify, (filter, predicate, (self.name, i)))
668 for i in range(self.npartitions)
669 }
670 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
671 return type(self)(graph, name, self.npartitions)
672
673 def random_sample(self, prob, random_state=None):
674 """Return elements from bag with probability of ``prob``.
675
676 Parameters
677 ----------
678 prob : float
679 A float between 0 and 1, representing the probability that each
680 element will be returned.
681 random_state : int or random.Random, optional
682 If an integer, will be used to seed a new ``random.Random`` object.
683 If provided, results in deterministic sampling.
684
685 Examples
686 --------
687 >>> import dask.bag as db
688 >>> b = db.from_sequence(range(10))
689 >>> b.random_sample(0.5, 43).compute()
690 [0, 1, 3, 4, 7, 9]
691 >>> b.random_sample(0.5, 43).compute()
692 [0, 1, 3, 4, 7, 9]
693 """
694 if not 0 <= prob <= 1:
695 raise ValueError("prob must be a number in the interval [0, 1]")
696 if not isinstance(random_state, Random):
697 random_state = Random(random_state)
698
699 name = "random-sample-%s" % tokenize(self, prob, random_state.getstate())
700 state_data = random_state_data_python(self.npartitions, random_state)
701 dsk = {
702 (name, i): (reify, (random_sample, (self.name, i), state, prob))
703 for i, state in zip(range(self.npartitions), state_data)
704 }
705 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
706 return type(self)(graph, name, self.npartitions)
707
708 def remove(self, predicate):
709 """Remove elements in collection that match predicate.
710
711 >>> def iseven(x):
712 ... return x % 2 == 0
713
714 >>> import dask.bag as db
715 >>> b = db.from_sequence(range(5))
716 >>> list(b.remove(iseven))
717 [1, 3]
718 """
719 name = f"remove-{funcname(predicate)}-{tokenize(self, predicate)}"
720 dsk = {
721 (name, i): (reify, (remove, predicate, (self.name, i)))
722 for i in range(self.npartitions)
723 }
724 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
725 return type(self)(graph, name, self.npartitions)
726
727 def map_partitions(self, func, *args, **kwargs):
728 """Apply a function to every partition across one or more bags.
729
730 Note that all ``Bag`` arguments must be partitioned identically.
731
732 Parameters
733 ----------
734 func : callable
735 The function to be called on every partition.
736 This function should expect an ``Iterator`` or ``Iterable`` for
737 every partition and should return an ``Iterator`` or ``Iterable``
738 in return.
739 *args, **kwargs : Bag, Item, Delayed, or object
740 Arguments and keyword arguments to pass to ``func``.
741 Partitions from this bag will be the first argument, and these will
742 be passed *after*.
743
744 Examples
745 --------
746 >>> import dask.bag as db
747 >>> b = db.from_sequence(range(1, 101), npartitions=10)
748 >>> def div(nums, den=1):
749 ... return [num / den for num in nums]
750
751 Using a python object:
752
753 >>> hi = b.max().compute()
754 >>> hi
755 100
756 >>> b.map_partitions(div, den=hi).take(5)
757 (0.01, 0.02, 0.03, 0.04, 0.05)
758
759 Using an ``Item``:
760
761 >>> b.map_partitions(div, den=b.max()).take(5)
762 (0.01, 0.02, 0.03, 0.04, 0.05)
763
764 Note that while both versions give the same output, the second forms a
765 single graph, and then computes everything at once, and in some cases
766 may be more efficient.
767 """
768 return map_partitions(func, self, *args, **kwargs)
769
770 def pluck(self, key, default=no_default):
771 """Select item from all tuples/dicts in collection.
772
773 >>> import dask.bag as db
774 >>> b = db.from_sequence([{'name': 'Alice', 'credits': [1, 2, 3]},
775 ... {'name': 'Bob', 'credits': [10, 20]}])
776 >>> list(b.pluck('name'))
777 ['Alice', 'Bob']
778 >>> list(b.pluck('credits').pluck(0))
779 [1, 10]
780 """
781 name = "pluck-" + tokenize(self, key, default)
782 key = quote(key)
783 if default is no_default:
784 dsk = {
785 (name, i): (list, (pluck, key, (self.name, i)))
786 for i in range(self.npartitions)
787 }
788 else:
789 dsk = {
790 (name, i): (list, (pluck, key, (self.name, i), default))
791 for i in range(self.npartitions)
792 }
793 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
794 return type(self)(graph, name, self.npartitions)
795
796 def unzip(self, n):
797 """Transform a bag of tuples to ``n`` bags of their elements.
798
799 Examples
800 --------
801 >>> import dask.bag as db
802 >>> b = db.from_sequence([(i, i + 1, i + 2) for i in range(10)])
803 >>> first, second, third = b.unzip(3)
804 >>> isinstance(first, db.Bag)
805 True
806 >>> first.compute()
807 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
808
809 Note that this is equivalent to:
810
811 >>> first, second, third = (b.pluck(i) for i in range(3))
812 """
813 return tuple(self.pluck(i) for i in range(n))
814
815 @wraps(to_textfiles)
816 def to_textfiles(
817 self,
818 path,
819 name_function=None,
820 compression="infer",
821 encoding=system_encoding,
822 compute=True,
823 storage_options=None,
824 last_endline=False,
825 **kwargs,
826 ):
827 return to_textfiles(
828 self,
829 path,
830 name_function,
831 compression,
832 encoding,
833 compute,
834 storage_options=storage_options,
835 last_endline=last_endline,
836 **kwargs,
837 )
838
839 @wraps(to_avro)
840 def to_avro(
841 self,
842 filename,
843 schema,
844 name_function=None,
845 storage_options=None,
846 codec="null",
847 sync_interval=16000,
848 metadata=None,
849 compute=True,
850 **kwargs,
851 ):
852 return to_avro(
853 self,
854 filename,
855 schema,
856 name_function,
857 storage_options,
858 codec,
859 sync_interval,
860 metadata,
861 compute,
862 **kwargs,
863 )
864
865 def fold(
866 self, binop, combine=None, initial=no_default, split_every=None, out_type=Item
867 ):
868 """Parallelizable reduction
869
870 Fold is like the builtin function ``reduce`` except that it works in
871 parallel. Fold takes two binary operator functions, one to reduce each
872 partition of our dataset and another to combine results between
873 partitions
874
875 1. ``binop``: Binary operator to reduce within each partition
876 2. ``combine``: Binary operator to combine results from binop
877
878 Sequentially this would look like the following:
879
880 >>> intermediates = [reduce(binop, part) for part in partitions] # doctest: +SKIP
881 >>> final = reduce(combine, intermediates) # doctest: +SKIP
882
883 If only one function is given then it is used for both functions
884 ``binop`` and ``combine`` as in the following example to compute the
885 sum:
886
887 >>> def add(x, y):
888 ... return x + y
889
890 >>> import dask.bag as db
891 >>> b = db.from_sequence(range(5))
892 >>> b.fold(add).compute()
893 10
894
895 In full form we provide both binary operators as well as their default
896 arguments
897
898 >>> b.fold(binop=add, combine=add, initial=0).compute()
899 10
900
901 More complex binary operators are also doable
902
903 >>> def add_to_set(acc, x):
904 ... ''' Add new element x to set acc '''
905 ... return acc | set([x])
906 >>> b.fold(add_to_set, set.union, initial=set()).compute()
907 {0, 1, 2, 3, 4}
908
909 See Also
910 --------
911
912 Bag.foldby
913 """
914 combine = combine or binop
915 if initial is not no_default:
916 return self.reduction(
917 curry(_reduce, binop, initial=initial),
918 curry(_reduce, combine),
919 split_every=split_every,
920 out_type=out_type,
921 )
922 else:
923 from tlz.curried import reduce
924
925 return self.reduction(
926 reduce(binop),
927 reduce(combine),
928 split_every=split_every,
929 out_type=out_type,
930 )
931
932 def frequencies(self, split_every=None, sort=False):
933 """Count number of occurrences of each distinct element.
934
935 >>> import dask.bag as db
936 >>> b = db.from_sequence(['Alice', 'Bob', 'Alice'])
937 >>> dict(b.frequencies()) # doctest: +SKIP
938 {'Alice': 2, 'Bob', 1}
939 """
940 result = self.reduction(
941 frequencies,
942 merge_frequencies,
943 out_type=Bag,
944 split_every=split_every,
945 name="frequencies",
946 ).map_partitions(dictitems)
947 if sort:
948 result = result.map_partitions(sorted, key=second, reverse=True)
949 return result
950
951 def topk(self, k, key=None, split_every=None):
952 """K largest elements in collection
953
954 Optionally ordered by some key function
955
956 >>> import dask.bag as db
957 >>> b = db.from_sequence([10, 3, 5, 7, 11, 4])
958 >>> list(b.topk(2))
959 [11, 10]
960
961 >>> list(b.topk(2, lambda x: -x))
962 [3, 4]
963 """
964 if key:
965 if callable(key) and takes_multiple_arguments(key):
966 key = partial(apply, key)
967 func = partial(topk, k, key=key)
968 else:
969 func = partial(topk, k)
970 return self.reduction(
971 func,
972 compose(func, toolz.concat),
973 out_type=Bag,
974 split_every=split_every,
975 name="topk",
976 )
977
978 def distinct(self, key=None):
979 """Distinct elements of collection
980
981 Unordered without repeats.
982
983 Parameters
984 ----------
985 key: {callable,str}
986 Defines uniqueness of items in bag by calling ``key`` on each item.
987 If a string is passed ``key`` is considered to be ``lambda x: x[key]``.
988
989 Examples
990 --------
991 >>> import dask.bag as db
992 >>> b = db.from_sequence(['Alice', 'Bob', 'Alice'])
993 >>> sorted(b.distinct())
994 ['Alice', 'Bob']
995 >>> b = db.from_sequence([{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Alice'}])
996 >>> b.distinct(key=lambda x: x['name']).compute()
997 [{'name': 'Alice'}, {'name': 'Bob'}]
998 >>> b.distinct(key='name').compute()
999 [{'name': 'Alice'}, {'name': 'Bob'}]
1000 """
1001 func = chunk_distinct if key is None else partial(chunk_distinct, key=key)
1002 agg = merge_distinct if key is None else partial(merge_distinct, key=key)
1003 return self.reduction(func, agg, out_type=Bag, name="distinct")
1004
1005 def reduction(
1006 self, perpartition, aggregate, split_every=None, out_type=Item, name=None
1007 ):
1008 """Reduce collection with reduction operators.
1009
1010 Parameters
1011 ----------
1012 perpartition: function
1013 reduction to apply to each partition
1014 aggregate: function
1015 reduction to apply to the results of all partitions
1016 split_every: int (optional)
1017 Group partitions into groups of this size while performing reduction
1018 Defaults to 8
1019 out_type: {Bag, Item}
1020 The out type of the result, Item if a single element, Bag if a list
1021 of elements. Defaults to Item.
1022
1023 Examples
1024 --------
1025 >>> import dask.bag as db
1026 >>> b = db.from_sequence(range(10))
1027 >>> b.reduction(sum, sum).compute()
1028 45
1029 """
1030 if split_every is None:
1031 split_every = 8
1032 if split_every is False:
1033 split_every = self.npartitions
1034
1035 token = tokenize(self, perpartition, aggregate, split_every)
1036 a = f"{name or funcname(perpartition)}-part-{token}"
1037 is_last = self.npartitions == 1
1038 dsk = {
1039 (a, i): (empty_safe_apply, perpartition, (self.name, i), is_last)
1040 for i in range(self.npartitions)
1041 }
1042 k = self.npartitions
1043 b = a
1044 fmt = f"{name or funcname(aggregate)}-aggregate-{token}"
1045 depth = 0
1046
1047 while k > split_every:
1048 c = fmt + str(depth)
1049 for i, inds in enumerate(partition_all(split_every, range(k))):
1050 dsk[(c, i)] = (
1051 empty_safe_aggregate,
1052 aggregate,
1053 [(b, j) for j in inds],
1054 False,
1055 )
1056
1057 k = i + 1
1058 b = c
1059 depth += 1
1060
1061 dsk[(fmt, 0)] = (
1062 empty_safe_aggregate,
1063 aggregate,
1064 [(b, j) for j in range(k)],
1065 True,
1066 )
1067
1068 graph = HighLevelGraph.from_collections(fmt, dsk, dependencies=[self])
1069 if out_type is Item:
1070 dsk[fmt] = dsk.pop((fmt, 0))
1071 return Item(graph, fmt)
1072 else:
1073 return Bag(graph, fmt, 1)
1074
1075 def sum(self, split_every=None):
1076 """Sum all elements"""
1077 return self.reduction(sum, sum, split_every=split_every)
1078
1079 def max(self, split_every=None):
1080 """Maximum element"""
1081 return self.reduction(max, max, split_every=split_every)
1082
1083 def min(self, split_every=None):
1084 """Minimum element"""
1085 return self.reduction(min, min, split_every=split_every)
1086
1087 def any(self, split_every=None):
1088 """Are any of the elements truthy?
1089
1090 Examples
1091 --------
1092 >>> import dask.bag as db
1093 >>> bool_bag = db.from_sequence([True, True, False])
1094 >>> bool_bag.any().compute()
1095 True
1096 """
1097 return self.reduction(any, any, split_every=split_every)
1098
1099 def all(self, split_every=None):
1100 """Are all elements truthy?
1101
1102 Examples
1103 --------
1104 >>> import dask.bag as db
1105 >>> bool_bag = db.from_sequence([True, True, False])
1106 >>> bool_bag.all().compute()
1107 False
1108 """
1109 return self.reduction(all, all, split_every=split_every)
1110
1111 def count(self, split_every=None):
1112 """Count the number of elements.
1113
1114 Examples
1115 --------
1116 >>> import dask.bag as db
1117 >>> numbers = db.from_sequence([1, 2, 3])
1118 >>> numbers.count().compute()
1119 3
1120 """
1121 return self.reduction(count, sum, split_every=split_every)
1122
1123 def mean(self):
1124 """Arithmetic mean"""
1125
1126 def mean_chunk(seq):
1127 total, n = 0.0, 0
1128 for x in seq:
1129 total += x
1130 n += 1
1131 return total, n
1132
1133 def mean_aggregate(x):
1134 totals, counts = list(zip(*x))
1135 return 1.0 * sum(totals) / sum(counts)
1136
1137 return self.reduction(mean_chunk, mean_aggregate, split_every=False)
1138
1139 def var(self, ddof=0):
1140 """Variance"""
1141 return self.reduction(
1142 chunk.var_chunk, partial(chunk.var_aggregate, ddof=ddof), split_every=False
1143 )
1144
1145 def std(self, ddof=0):
1146 """Standard deviation"""
1147 return self.var(ddof=ddof).apply(math.sqrt)
1148
1149 def join(self, other, on_self, on_other=None):
1150 """Joins collection with another collection.
1151
1152 Other collection must be one of the following:
1153
1154 1. An iterable. We recommend tuples over lists for internal
1155 performance reasons.
1156 2. A delayed object, pointing to a tuple. This is recommended if the
1157 other collection is sizable and you're using the distributed
1158 scheduler. Dask is able to pass around data wrapped in delayed
1159 objects with greater sophistication.
1160 3. A Bag with a single partition
1161
1162 You might also consider Dask Dataframe, whose join operations are much
1163 more heavily optimized.
1164
1165 Parameters
1166 ----------
1167 other: Iterable, Delayed, Bag
1168 Other collection on which to join
1169 on_self: callable
1170 Function to call on elements in this collection to determine a
1171 match
1172 on_other: callable (defaults to on_self)
1173 Function to call on elements in the other collection to determine a
1174 match
1175
1176 Examples
1177 --------
1178 >>> import dask.bag as db
1179 >>> people = db.from_sequence(['Alice', 'Bob', 'Charlie'])
1180 >>> fruit = ['Apple', 'Apricot', 'Banana']
1181 >>> list(people.join(fruit, lambda x: x[0]))
1182 [('Apple', 'Alice'), ('Apricot', 'Alice'), ('Banana', 'Bob')]
1183 """
1184 name = "join-" + tokenize(self, other, on_self, on_other)
1185 dsk = {}
1186 if isinstance(other, Bag):
1187 if other.npartitions == 1:
1188 dsk.update(other.dask)
1189 other = other.__dask_keys__()[0]
1190 dsk["join-%s-other" % name] = (list, other)
1191 else:
1192 msg = (
1193 "Multi-bag joins are not implemented. "
1194 "We recommend Dask dataframe if appropriate"
1195 )
1196 raise NotImplementedError(msg)
1197 elif isinstance(other, Delayed):
1198 dsk.update(other.dask)
1199 other = other._key
1200 elif isinstance(other, Iterable):
1201 other = other
1202 else:
1203 msg = (
1204 "Joined argument must be single-partition Bag, "
1205 " delayed object, or Iterable, got %s" % type(other).__name
1206 )
1207 raise TypeError(msg)
1208
1209 if on_other is None:
1210 on_other = on_self
1211
1212 for i in range(self.npartitions):
1213 dsk[(name, i)] = (list, (join, on_other, other, on_self, (self.name, i)))
1214
1215 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
1216 return type(self)(graph, name, self.npartitions)
1217
1218 def product(self, other):
1219 """Cartesian product between two bags."""
1220 assert isinstance(other, Bag)
1221 name = "product-" + tokenize(self, other)
1222 n, m = self.npartitions, other.npartitions
1223 dsk = {
1224 (name, i * m + j): (
1225 list,
1226 (itertools.product, (self.name, i), (other.name, j)),
1227 )
1228 for i in range(n)
1229 for j in range(m)
1230 }
1231 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self, other])
1232 return type(self)(graph, name, n * m)
1233
1234 def foldby(
1235 self,
1236 key,
1237 binop,
1238 initial=no_default,
1239 combine=None,
1240 combine_initial=no_default,
1241 split_every=None,
1242 ):
1243 """Combined reduction and groupby.
1244
1245 Foldby provides a combined groupby and reduce for efficient parallel
1246 split-apply-combine tasks.
1247
1248 The computation
1249
1250 >>> b.foldby(key, binop, init) # doctest: +SKIP
1251
1252 is equivalent to the following:
1253
1254 >>> def reduction(group): # doctest: +SKIP
1255 ... return reduce(binop, group, init) # doctest: +SKIP
1256
1257 >>> b.groupby(key).map(lambda (k, v): (k, reduction(v)))# doctest: +SKIP
1258
1259 But uses minimal communication and so is *much* faster.
1260
1261 >>> import dask.bag as db
1262 >>> b = db.from_sequence(range(10))
1263 >>> iseven = lambda x: x % 2 == 0
1264 >>> add = lambda x, y: x + y
1265 >>> dict(b.foldby(iseven, add))
1266 {True: 20, False: 25}
1267
1268 **Key Function**
1269
1270 The key function determines how to group the elements in your bag.
1271 In the common case where your bag holds dictionaries then the key
1272 function often gets out one of those elements.
1273
1274 >>> def key(x):
1275 ... return x['name']
1276
1277 This case is so common that it is special cased, and if you provide a
1278 key that is not a callable function then dask.bag will turn it into one
1279 automatically. The following are equivalent:
1280
1281 >>> b.foldby(lambda x: x['name'], ...) # doctest: +SKIP
1282 >>> b.foldby('name', ...) # doctest: +SKIP
1283
1284 **Binops**
1285
1286 It can be tricky to construct the right binary operators to perform
1287 analytic queries. The ``foldby`` method accepts two binary operators,
1288 ``binop`` and ``combine``. Binary operators two inputs and output must
1289 have the same type.
1290
1291 Binop takes a running total and a new element and produces a new total:
1292
1293 >>> def binop(total, x):
1294 ... return total + x['amount']
1295
1296 Combine takes two totals and combines them:
1297
1298 >>> def combine(total1, total2):
1299 ... return total1 + total2
1300
1301 Each of these binary operators may have a default first value for
1302 total, before any other value is seen. For addition binary operators
1303 like above this is often ``0`` or the identity element for your
1304 operation.
1305
1306 **split_every**
1307
1308 Group partitions into groups of this size while performing reduction.
1309 Defaults to 8.
1310
1311 >>> b.foldby('name', binop, 0, combine, 0) # doctest: +SKIP
1312
1313 Examples
1314 --------
1315
1316 We can compute the maximum of some ``(key, value)`` pairs, grouped
1317 by the ``key``. (You might be better off converting the ``Bag`` to
1318 a ``dask.dataframe`` and using its groupby).
1319
1320 >>> import random
1321 >>> import dask.bag as db
1322
1323 >>> tokens = list('abcdefg')
1324 >>> values = range(10000)
1325 >>> a = [(random.choice(tokens), random.choice(values))
1326 ... for _ in range(100)]
1327 >>> a[:2] # doctest: +SKIP
1328 [('g', 676), ('a', 871)]
1329
1330 >>> a = db.from_sequence(a)
1331
1332 >>> def binop(t, x):
1333 ... return max((t, x), key=lambda x: x[1])
1334
1335 >>> a.foldby(lambda x: x[0], binop).compute() # doctest: +SKIP
1336 [('g', ('g', 984)),
1337 ('a', ('a', 871)),
1338 ('b', ('b', 999)),
1339 ('c', ('c', 765)),
1340 ('f', ('f', 955)),
1341 ('e', ('e', 991)),
1342 ('d', ('d', 854))]
1343
1344 See Also
1345 --------
1346
1347 toolz.reduceby
1348 pyspark.combineByKey
1349 """
1350 if split_every is None:
1351 split_every = 8
1352 if split_every is False:
1353 split_every = self.npartitions
1354
1355 token = tokenize(self, key, binop, initial, combine, combine_initial)
1356 a = "foldby-a-" + token
1357 if combine is None:
1358 combine = binop
1359 if initial is not no_default:
1360 dsk = {
1361 (a, i): (reduceby, key, binop, (self.name, i), initial)
1362 for i in range(self.npartitions)
1363 }
1364 else:
1365 dsk = {
1366 (a, i): (reduceby, key, binop, (self.name, i))
1367 for i in range(self.npartitions)
1368 }
1369
1370 combine2 = partial(chunk.foldby_combine2, combine)
1371 depth = 0
1372 k = self.npartitions
1373 b = a
1374 while k > split_every:
1375 c = b + str(depth)
1376 if combine_initial is not no_default:
1377 for i, inds in enumerate(partition_all(split_every, range(k))):
1378 dsk[(c, i)] = (
1379 reduceby,
1380 0,
1381 combine2,
1382 (toolz.concat, (map, dictitems, [(b, j) for j in inds])),
1383 combine_initial,
1384 )
1385 else:
1386 for i, inds in enumerate(partition_all(split_every, range(k))):
1387 dsk[(c, i)] = (
1388 merge_with,
1389 (partial, reduce, combine),
1390 [(b, j) for j in inds],
1391 )
1392
1393 k = i + 1
1394 b = c
1395 depth += 1
1396
1397 e = "foldby-b-" + token
1398 if combine_initial is not no_default:
1399 dsk[(e, 0)] = (
1400 dictitems,
1401 (
1402 reduceby,
1403 0,
1404 combine2,
1405 (toolz.concat, (map, dictitems, [(b, j) for j in range(k)])),
1406 combine_initial,
1407 ),
1408 )
1409 else:
1410 dsk[(e, 0)] = (
1411 dictitems,
1412 (merge_with, (partial, reduce, combine), [(b, j) for j in range(k)]),
1413 )
1414
1415 graph = HighLevelGraph.from_collections(e, dsk, dependencies=[self])
1416 return type(self)(graph, e, 1)
1417
1418 def take(self, k, npartitions=1, compute=True, warn=True):
1419 """Take the first k elements.
1420
1421 Parameters
1422 ----------
1423 k : int
1424 The number of elements to return
1425 npartitions : int, optional
1426 Elements are only taken from the first ``npartitions``, with a
1427 default of 1. If there are fewer than ``k`` rows in the first
1428 ``npartitions`` a warning will be raised and any found rows
1429 returned. Pass -1 to use all partitions.
1430 compute : bool, optional
1431 Whether to compute the result, default is True.
1432 warn : bool, optional
1433 Whether to warn if the number of elements returned is less than
1434 requested, default is True.
1435
1436 >>> import dask.bag as db
1437 >>> b = db.from_sequence(range(1_000))
1438 >>> b.take(3)
1439 (0, 1, 2)
1440 """
1441
1442 if npartitions <= -1:
1443 npartitions = self.npartitions
1444 if npartitions > self.npartitions:
1445 raise ValueError(
1446 "only {} partitions, take "
1447 "received {}".format(self.npartitions, npartitions)
1448 )
1449
1450 token = tokenize(self, k, npartitions)
1451 name = "take-" + token
1452
1453 if npartitions > 1:
1454 name_p = "take-partial-" + token
1455
1456 dsk = {}
1457 for i in range(npartitions):
1458 dsk[(name_p, i)] = (list, (take, k, (self.name, i)))
1459
1460 concat = (toolz.concat, ([(name_p, i) for i in range(npartitions)]))
1461 dsk[(name, 0)] = (safe_take, k, concat, warn)
1462 else:
1463 dsk = {(name, 0): (safe_take, k, (self.name, 0), warn)}
1464
1465 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
1466 b = Bag(graph, name, 1)
1467
1468 if compute:
1469 return tuple(b.compute())
1470 else:
1471 return b
1472
1473 def flatten(self):
1474 """Concatenate nested lists into one long list.
1475
1476 >>> import dask.bag as db
1477 >>> b = db.from_sequence([[1], [2, 3]])
1478 >>> list(b)
1479 [[1], [2, 3]]
1480
1481 >>> list(b.flatten())
1482 [1, 2, 3]
1483 """
1484 name = "flatten-" + tokenize(self)
1485 dsk = {
1486 (name, i): (list, (toolz.concat, (self.name, i)))
1487 for i in range(self.npartitions)
1488 }
1489 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[self])
1490 return type(self)(graph, name, self.npartitions)
1491
1492 def __iter__(self):
1493 return iter(self.compute())
1494
1495 def groupby(
1496 self,
1497 grouper,
1498 method=None,
1499 npartitions=None,
1500 blocksize=2**20,
1501 max_branch=None,
1502 shuffle=None,
1503 ):
1504 """Group collection by key function
1505
1506 This requires a full dataset read, serialization and shuffle.
1507 This is expensive. If possible you should use ``foldby``.
1508
1509 Parameters
1510 ----------
1511 grouper: function
1512 Function on which to group elements
1513 shuffle: str
1514 Either 'disk' for an on-disk shuffle or 'tasks' to use the task
1515 scheduling framework. Use 'disk' if you are on a single machine
1516 and 'tasks' if you are on a distributed cluster.
1517 npartitions: int
1518 If using the disk-based shuffle, the number of output partitions
1519 blocksize: int
1520 If using the disk-based shuffle, the size of shuffle blocks (bytes)
1521 max_branch: int
1522 If using the task-based shuffle, the amount of splitting each
1523 partition undergoes. Increase this for fewer copies but more
1524 scheduler overhead.
1525
1526 Examples
1527 --------
1528 >>> import dask.bag as db
1529 >>> b = db.from_sequence(range(10))
1530 >>> iseven = lambda x: x % 2 == 0
1531 >>> dict(b.groupby(iseven)) # doctest: +SKIP
1532 {True: [0, 2, 4, 6, 8], False: [1, 3, 5, 7, 9]}
1533
1534 See Also
1535 --------
1536 Bag.foldby
1537 """
1538 if method is not None:
1539 raise Exception("The method= keyword has been moved to shuffle=")
1540 if shuffle is None:
1541 try:
1542 shuffle = get_default_shuffle_method()
1543 except ImportError:
1544 shuffle = "tasks"
1545 else:
1546 if shuffle == "p2p":
1547 # Not implemented for Bags
1548 shuffle = "tasks"
1549 if shuffle == "disk":
1550 return groupby_disk(
1551 self, grouper, npartitions=npartitions, blocksize=blocksize
1552 )
1553 elif shuffle == "tasks":
1554 return groupby_tasks(self, grouper, max_branch=max_branch)
1555 else:
1556 msg = "Shuffle must be 'disk' or 'tasks'"
1557 raise NotImplementedError(msg)
1558
1559 def to_dataframe(self, meta=None, columns=None, optimize_graph=True):
1560 """Create Dask Dataframe from a Dask Bag.
1561
1562 Bag should contain tuples, dict records, or scalars.
1563
1564 Index will not be particularly meaningful. Use ``reindex`` afterwards
1565 if necessary.
1566
1567 Parameters
1568 ----------
1569 meta : pd.DataFrame, dict, iterable, optional
1570 An empty ``pd.DataFrame`` that matches the dtypes and column names
1571 of the output. This metadata is necessary for many algorithms in
1572 dask dataframe to work. For ease of use, some alternative inputs
1573 are also available. Instead of a ``DataFrame``, a ``dict`` of
1574 ``{name: dtype}`` or iterable of ``(name, dtype)`` can be provided.
1575 If not provided or a list, a single element from the first
1576 partition will be computed, triggering a potentially expensive call
1577 to ``compute``. This may lead to unexpected results, so providing
1578 ``meta`` is recommended. For more information, see
1579 ``dask.dataframe.utils.make_meta``.
1580 columns : sequence, optional
1581 Column names to use. If the passed data do not have names
1582 associated with them, this argument provides names for the columns.
1583 Otherwise this argument indicates the order of the columns in the
1584 result (any names not found in the data will become all-NA
1585 columns). Note that if ``meta`` is provided, column names will be
1586 taken from there and this parameter is invalid.
1587 optimize_graph : bool, optional
1588 If True [default], the graph is optimized before converting into
1589 :class:`dask.dataframe.DataFrame`.
1590
1591
1592 Examples
1593 --------
1594 >>> import dask.bag as db
1595 >>> b = db.from_sequence([{'name': 'Alice', 'balance': 100},
1596 ... {'name': 'Bob', 'balance': 200},
1597 ... {'name': 'Charlie', 'balance': 300}],
1598 ... npartitions=2)
1599 >>> df = b.to_dataframe()
1600
1601 >>> df.compute()
1602 name balance
1603 0 Alice 100
1604 1 Bob 200
1605 0 Charlie 300
1606 """
1607 import pandas as pd
1608
1609 import dask.dataframe as dd
1610
1611 if meta is None:
1612 head = self.take(1, warn=False)
1613 if len(head) == 0:
1614 raise ValueError(
1615 "`dask.bag.Bag.to_dataframe` failed to "
1616 "properly infer metadata, please pass in "
1617 "metadata via the `meta` keyword"
1618 )
1619 meta = pd.DataFrame(list(head), columns=columns)
1620 elif columns is not None:
1621 raise ValueError("Can't specify both `meta` and `columns`")
1622 else:
1623 meta = dd.utils.make_meta(meta, parent_meta=pd.DataFrame())
1624 # Serializing the columns and dtypes is much smaller than serializing
1625 # the empty frame
1626 cols = list(meta.columns)
1627 dtypes = meta.dtypes.to_dict()
1628
1629 dfs = self.map_partitions(to_dataframe, cols, dtypes)
1630 if optimize_graph:
1631 dsk = self.__dask_optimize__(dfs.dask, dfs.__dask_keys__())
1632 else:
1633 dsk = dfs.dask
1634
1635 divisions = [None] * (self.npartitions + 1)
1636 if not dd._dask_expr_enabled():
1637 return dd.DataFrame(dsk, dfs.name, meta, divisions)
1638 else:
1639 from dask_expr import from_legacy_dataframe
1640
1641 from dask.dataframe.core import DataFrame
1642
1643 df = DataFrame(dsk, dfs.name, meta, divisions)
1644 return from_legacy_dataframe(df)
1645
1646 def to_delayed(self, optimize_graph=True):
1647 """Convert into a list of ``dask.delayed`` objects, one per partition.
1648
1649 Parameters
1650 ----------
1651 optimize_graph : bool, optional
1652 If True [default], the graph is optimized before converting into
1653 ``dask.delayed`` objects.
1654
1655 See Also
1656 --------
1657 dask.bag.from_delayed
1658 """
1659 from dask.delayed import Delayed
1660
1661 keys = self.__dask_keys__()
1662 dsk = self.__dask_graph__()
1663 layer = self.name
1664 if optimize_graph:
1665 dsk = self.__dask_optimize__(dsk, keys)
1666 layer = "delayed-" + layer
1667 dsk = HighLevelGraph.from_collections(layer, dsk, dependencies=())
1668 return [Delayed(k, dsk, layer=layer) for k in keys]
1669
1670 def repartition(self, npartitions=None, partition_size=None):
1671 """Repartition Bag across new divisions.
1672
1673 Parameters
1674 ----------
1675 npartitions : int, optional
1676 Number of partitions of output.
1677 partition_size : int or string, optional
1678 Max number of bytes of memory for each partition. Use numbers or
1679 strings like 5MB.
1680
1681 .. warning::
1682
1683 This keyword argument triggers computation to determine
1684 the memory size of each partition, which may be expensive.
1685
1686 Notes
1687 -----
1688 Exactly one of ``npartitions`` or ``partition_size`` should be specified.
1689 A ``ValueError`` will be raised when that is not the case.
1690
1691 Examples
1692 --------
1693 >>> b.repartition(5) # set to have 5 partitions # doctest: +SKIP
1694 """
1695 if sum([partition_size is not None, npartitions is not None]) != 1:
1696 raise ValueError(
1697 "Please provide exactly one ``npartitions`` or ``partition_size`` keyword arguments"
1698 )
1699 if npartitions is not None:
1700 return repartition_npartitions(self, npartitions)
1701 elif partition_size is not None:
1702 return repartition_size(self, partition_size)
1703
1704 def accumulate(self, binop, initial=no_default):
1705 """Repeatedly apply binary function to a sequence, accumulating results.
1706
1707 This assumes that the bag is ordered. While this is typically the case
1708 not all Dask.bag functions preserve this property.
1709
1710 Examples
1711 --------
1712 >>> import dask.bag as db
1713 >>> from operator import add
1714 >>> b = db.from_sequence([1, 2, 3, 4, 5], npartitions=2)
1715 >>> b.accumulate(add).compute()
1716 [1, 3, 6, 10, 15]
1717
1718 Accumulate also takes an optional argument that will be used as the
1719 first value.
1720
1721 >>> b.accumulate(add, initial=-1).compute()
1722 [-1, 0, 2, 5, 9, 14]
1723 """
1724 token = tokenize(self, binop, initial)
1725 binop_name = funcname(binop)
1726 a = f"{binop_name}-part-{token}"
1727 b = f"{binop_name}-first-{token}"
1728 c = f"{binop_name}-second-{token}"
1729 dsk = {
1730 (a, 0): (accumulate_part, binop, (self.name, 0), initial, True),
1731 (b, 0): (first, (a, 0)),
1732 (c, 0): (second, (a, 0)),
1733 }
1734 for i in range(1, self.npartitions):
1735 dsk[(a, i)] = (accumulate_part, binop, (self.name, i), (c, i - 1))
1736 dsk[(b, i)] = (first, (a, i))
1737 dsk[(c, i)] = (second, (a, i))
1738 graph = HighLevelGraph.from_collections(b, dsk, dependencies=[self])
1739 return Bag(graph, b, self.npartitions)
1740
1741
1742 def accumulate_part(binop, seq, initial, is_first=False):
1743 if initial is no_default:
1744 res = list(accumulate(binop, seq))
1745 else:
1746 res = list(accumulate(binop, seq, initial=initial))
1747 if is_first:
1748 return res, res[-1] if res else [], initial
1749 return res[1:], res[-1]
1750
1751
1752 def partition(grouper, sequence, npartitions, p, nelements=2**20):
1753 """Partition a bag along a grouper, store partitions on disk."""
1754 for block in partition_all(nelements, sequence):
1755 d = groupby(grouper, block)
1756 d2 = defaultdict(list)
1757 for k, v in d.items():
1758 d2[abs(int(tokenize(k), 16)) % npartitions].extend(v)
1759 p.append(d2, fsync=True)
1760 return p
1761
1762
1763 def collect(grouper, group, p, barrier_token):
1764 """Collect partitions from disk and yield k,v group pairs."""
1765 d = groupby(grouper, p.get(group, lock=False))
1766 return list(d.items())
1767
1768
1769 def from_sequence(seq, partition_size=None, npartitions=None):
1770 """Create a dask Bag from Python sequence.
1771
1772 This sequence should be relatively small in memory. Dask Bag works
1773 best when it handles loading your data itself. Commonly we load a
1774 sequence of filenames into a Bag and then use ``.map`` to open them.
1775
1776 Parameters
1777 ----------
1778 seq: Iterable
1779 A sequence of elements to put into the dask
1780 partition_size: int (optional)
1781 The length of each partition
1782 npartitions: int (optional)
1783 The number of desired partitions
1784
1785 It is best to provide either ``partition_size`` or ``npartitions``
1786 (though not both.)
1787
1788 Examples
1789 --------
1790 >>> import dask.bag as db
1791 >>> b = db.from_sequence(['Alice', 'Bob', 'Chuck'], partition_size=2)
1792
1793 See Also
1794 --------
1795 read_text: Create bag from text files
1796 """
1797 seq = list(seq)
1798 if npartitions and not partition_size:
1799 if len(seq) <= 100:
1800 partition_size = int(math.ceil(len(seq) / npartitions))
1801 else:
1802 partition_size = max(1, int(math.floor(len(seq) / npartitions)))
1803 if npartitions is None and partition_size is None:
1804 if len(seq) <= 100:
1805 partition_size = 1
1806 else:
1807 partition_size = max(1, math.ceil(math.sqrt(len(seq)) / math.sqrt(100)))
1808
1809 parts = list(partition_all(partition_size, seq))
1810 name = "from_sequence-" + tokenize(seq, partition_size)
1811 if len(parts) > 0:
1812 d = {(name, i): list(part) for i, part in enumerate(parts)}
1813 else:
1814 d = {(name, 0): []}
1815
1816 return Bag(d, name, len(d))
1817
1818
1819 def from_url(urls):
1820 """Create a dask Bag from a url.
1821
1822 Examples
1823 --------
1824 >>> a = from_url('http://raw.githubusercontent.com/dask/dask/main/README.rst')
1825 >>> a.npartitions
1826 1
1827
1828 >>> a.take(8) # doctest: +SKIP
1829 (b'Dask\\n',
1830 b'====\\n',
1831 b'\\n',
1832 b'|Build Status| |Coverage| |Doc Status| |Discourse| |Version Status| |NumFOCUS|\\n',
1833 b'\\n',
1834 b'Dask is a flexible parallel computing library for analytics. See\\n',
1835 b'documentation_ for more information.\\n',
1836 b'\\n')
1837
1838 >>> b = from_url(['http://github.com', 'http://google.com'])
1839 >>> b.npartitions
1840 2
1841 """
1842 if isinstance(urls, str):
1843 urls = [urls]
1844 name = "from_url-" + uuid.uuid4().hex
1845 dsk = {}
1846 for i, u in enumerate(urls):
1847 dsk[(name, i)] = (list, (urlopen, u))
1848 return Bag(dsk, name, len(urls))
1849
1850
1851 def dictitems(d):
1852 """A pickleable version of dict.items
1853
1854 >>> dictitems({'x': 1})
1855 [('x', 1)]
1856 """
1857 return list(d.items())
1858
1859
1860 def concat(bags):
1861 """Concatenate many bags together, unioning all elements.
1862
1863 >>> import dask.bag as db
1864 >>> a = db.from_sequence([1, 2, 3])
1865 >>> b = db.from_sequence([4, 5, 6])
1866 >>> c = db.concat([a, b])
1867
1868 >>> list(c)
1869 [1, 2, 3, 4, 5, 6]
1870 """
1871 name = "concat-" + tokenize(*bags)
1872 counter = itertools.count(0)
1873 dsk = {(name, next(counter)): key for bag in bags for key in bag.__dask_keys__()}
1874 graph = HighLevelGraph.from_collections(name, dsk, dependencies=bags)
1875 return Bag(graph, name, len(dsk))
1876
1877
1878 def reify(seq):
1879 if isinstance(seq, Iterator):
1880 seq = list(seq)
1881 if len(seq) and isinstance(seq[0], Iterator):
1882 seq = list(map(list, seq))
1883 return seq
1884
1885
1886 def from_delayed(values):
1887 """Create bag from many dask Delayed objects.
1888
1889 These objects will become the partitions of the resulting Bag. They should
1890 evaluate to a ``list`` or some other concrete sequence.
1891
1892 Parameters
1893 ----------
1894 values: list of delayed values
1895 An iterable of dask Delayed objects. Each evaluating to a list.
1896
1897 Returns
1898 -------
1899 Bag
1900
1901 Examples
1902 --------
1903 >>> x, y, z = [delayed(load_sequence_from_file)(fn)
1904 ... for fn in filenames] # doctest: +SKIP
1905 >>> b = from_delayed([x, y, z]) # doctest: +SKIP
1906
1907 See also
1908 --------
1909 dask.delayed
1910 """
1911 from dask.delayed import Delayed, delayed
1912
1913 if isinstance(values, Delayed):
1914 values = [values]
1915 values = [
1916 delayed(v) if not isinstance(v, Delayed) and hasattr(v, "key") else v
1917 for v in values
1918 ]
1919
1920 name = "bag-from-delayed-" + tokenize(*values)
1921 names = [(name, i) for i in range(len(values))]
1922 values2 = [(reify, v.key) for v in values]
1923 dsk = dict(zip(names, values2))
1924
1925 graph = HighLevelGraph.from_collections(name, dsk, dependencies=values)
1926 return Bag(graph, name, len(values))
1927
1928
1929 def chunk_distinct(seq, key=None):
1930 if key is not None and not callable(key):
1931 key = partial(chunk.getitem, key=key)
1932 return list(unique(seq, key=key))
1933
1934
1935 def merge_distinct(seqs, key=None):
1936 return chunk_distinct(toolz.concat(seqs), key=key)
1937
1938
1939 def merge_frequencies(seqs):
1940 if isinstance(seqs, Iterable):
1941 seqs = list(seqs)
1942 if not seqs:
1943 return {}
1944 first, rest = seqs[0], seqs[1:]
1945 if not rest:
1946 return first
1947 out = defaultdict(int)
1948 out.update(first)
1949 for d in rest:
1950 for k, v in d.items():
1951 out[k] += v
1952 return out
1953
1954
1955 def bag_range(n, npartitions):
1956 """Numbers from zero to n
1957
1958 Examples
1959 --------
1960
1961 >>> import dask.bag as db
1962 >>> b = db.range(5, npartitions=2)
1963 >>> list(b)
1964 [0, 1, 2, 3, 4]
1965 """
1966 size = n // npartitions
1967 name = "range-%d-npartitions-%d" % (n, npartitions)
1968 ijs = list(enumerate(take(npartitions, range(0, n, size))))
1969 dsk = {(name, i): (reify, (range, j, min(j + size, n))) for i, j in ijs}
1970
1971 if n % npartitions != 0:
1972 i, j = ijs[-1]
1973 dsk[(name, i)] = (reify, (range, j, n))
1974
1975 return Bag(dsk, name, npartitions)
1976
1977
1978 def bag_zip(*bags):
1979 """Partition-wise bag zip
1980
1981 All passed bags must have the same number of partitions.
1982
1983 NOTE: corresponding partitions should have the same length; if they do not,
1984 the "extra" elements from the longer partition(s) will be dropped. If you
1985 have this case chances are that what you really need is a data alignment
1986 mechanism like pandas's, and not a missing value filler like zip_longest.
1987
1988 Examples
1989 --------
1990
1991 Correct usage:
1992
1993 >>> import dask.bag as db
1994 >>> evens = db.from_sequence(range(0, 10, 2), partition_size=4)
1995 >>> odds = db.from_sequence(range(1, 10, 2), partition_size=4)
1996 >>> pairs = db.zip(evens, odds)
1997 >>> list(pairs)
1998 [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
1999
2000 Incorrect usage:
2001
2002 >>> numbers = db.range(31, npartitions=1)
2003 >>> fizz = numbers.filter(lambda n: n % 3 == 0)
2004 >>> buzz = numbers.filter(lambda n: n % 5 == 0)
2005 >>> fizzbuzz = db.zip(fizz, buzz)
2006 >>> list(fizzbuzz)
2007 [(0, 0), (3, 5), (6, 10), (9, 15), (12, 20), (15, 25), (18, 30)]
2008
2009 When what you really wanted was more along the lines of the following:
2010
2011 >>> list(fizzbuzz) # doctest: +SKIP
2012 (0, 0), (3, None), (None, 5), (6, None), (9, None), (None, 10),
2013 (12, None), (15, 15), (18, None), (None, 20),
2014 (21, None), (24, None), (None, 25), (27, None), (30, 30)
2015 """
2016 npartitions = bags[0].npartitions
2017 assert all(bag.npartitions == npartitions for bag in bags)
2018 # TODO: do more checks
2019
2020 name = "zip-" + tokenize(*bags)
2021 dsk = {
2022 (name, i): (reify, (zip,) + tuple((bag.name, i) for bag in bags))
2023 for i in range(npartitions)
2024 }
2025 graph = HighLevelGraph.from_collections(name, dsk, dependencies=bags)
2026 return Bag(graph, name, npartitions)
2027
2028
2029 def map_chunk(f, iters, iter_kwarg_keys=None, kwargs=None):
2030 """Map ``f`` across one or more iterables, maybe with keyword arguments.
2031
2032 Low-level function used in ``bag_map``, not user facing.
2033
2034 Arguments
2035 ---------
2036 f : callable
2037 iters : List[Iterable]
2038 iter_kwarg_keys : List[str] or None
2039 Keyword names to use for pair with the tail end of ``iters``, allowing
2040 keyword arguments to be passed in from iterators.
2041 kwargs : dict or None
2042 Additional constant keyword arguments to use on every call to ``f``.
2043 """
2044 if kwargs:
2045 f = partial(f, **kwargs)
2046 iters = [iter(a) for a in iters]
2047 return _MapChunk(f, iters, kwarg_keys=iter_kwarg_keys)
2048
2049
2050 class _MapChunk(Iterator):
2051 def __init__(self, f, iters, kwarg_keys=None):
2052 self.f = f
2053 self.iters = iters
2054 self.kwarg_keys = kwarg_keys or ()
2055 self.nkws = len(self.kwarg_keys)
2056
2057 def __next__(self):
2058 try:
2059 vals = [next(i) for i in self.iters]
2060 except StopIteration:
2061 self.check_all_iterators_consumed()
2062 raise
2063
2064 if self.nkws:
2065 args = vals[: -self.nkws]
2066 kwargs = dict(zip(self.kwarg_keys, vals[-self.nkws :]))
2067 return self.f(*args, **kwargs)
2068 return self.f(*vals)
2069
2070 def check_all_iterators_consumed(self):
2071 if len(self.iters) > 1:
2072 for i in self.iters:
2073 if isinstance(i, itertools.repeat):
2074 continue
2075 try:
2076 next(i)
2077 except StopIteration:
2078 pass
2079 else:
2080 msg = (
2081 "map called with multiple bags that aren't identically "
2082 "partitioned. Please ensure that all bag arguments "
2083 "have the same partition lengths"
2084 )
2085 raise ValueError(msg)
2086
2087
2088 def starmap_chunk(f, x, kwargs):
2089 if kwargs:
2090 f = partial(f, **kwargs)
2091 return itertools.starmap(f, x)
2092
2093
2094 def unpack_scalar_dask_kwargs(kwargs):
2095 """Extracts dask values from kwargs.
2096
2097 Currently only ``dask.bag.Item`` and ``dask.delayed.Delayed`` are
2098 supported. Returns a merged dask graph and a task resulting in a keyword
2099 dict.
2100 """
2101 kwargs2 = {}
2102 dependencies = []
2103 for k, v in kwargs.items():
2104 vv, collections = _blockwise_unpack_collections_task_spec(v)
2105 if not collections:
2106 kwargs2[k] = v
2107 else:
2108 kwargs2[k] = vv
2109 dependencies.extend(collections)
2110 return kwargs2, dependencies
2111
2112
2113 def bag_map(func, *args, **kwargs):
2114 """Apply a function elementwise across one or more bags.
2115
2116 Note that all ``Bag`` arguments must be partitioned identically.
2117
2118 Parameters
2119 ----------
2120 func : callable
2121 *args, **kwargs : Bag, Item, Delayed, or object
2122 Arguments and keyword arguments to pass to ``func``. Non-Bag args/kwargs
2123 are broadcasted across all calls to ``func``.
2124
2125 Notes
2126 -----
2127 For calls with multiple `Bag` arguments, corresponding partitions should
2128 have the same length; if they do not, the call will error at compute time.
2129
2130 Examples
2131 --------
2132 >>> import dask.bag as db
2133 >>> b = db.from_sequence(range(5), npartitions=2)
2134 >>> b2 = db.from_sequence(range(5, 10), npartitions=2)
2135
2136 Apply a function to all elements in a bag:
2137
2138 >>> db.map(lambda x: x + 1, b).compute()
2139 [1, 2, 3, 4, 5]
2140
2141 Apply a function with arguments from multiple bags:
2142
2143 >>> from operator import add
2144 >>> db.map(add, b, b2).compute()
2145 [5, 7, 9, 11, 13]
2146
2147 Non-bag arguments are broadcast across all calls to the mapped function:
2148
2149 >>> db.map(add, b, 1).compute()
2150 [1, 2, 3, 4, 5]
2151
2152 Keyword arguments are also supported, and have the same semantics as
2153 regular arguments:
2154
2155 >>> def myadd(x, y=0):
2156 ... return x + y
2157 >>> db.map(myadd, b, y=b2).compute()
2158 [5, 7, 9, 11, 13]
2159 >>> db.map(myadd, b, y=1).compute()
2160 [1, 2, 3, 4, 5]
2161
2162 Both arguments and keyword arguments can also be instances of
2163 ``dask.bag.Item`` or ``dask.delayed.Delayed``. Here we'll add the max value
2164 in the bag to each element:
2165
2166 >>> db.map(myadd, b, b.max()).compute()
2167 [4, 5, 6, 7, 8]
2168 """
2169 name = "{}-{}".format(funcname(func), tokenize(func, "map", *args, **kwargs))
2170 dependencies = []
2171
2172 bags = []
2173 args2 = []
2174 for a in args:
2175 if isinstance(a, Bag):
2176 bags.append(a)
2177 args2.append(a)
2178 elif isinstance(a, (Item, Delayed)):
2179 dependencies.append(a)
2180 args2.append((itertools.repeat, a.key))
2181 else:
2182 args2.append((itertools.repeat, a))
2183
2184 bag_kwargs = {}
2185 other_kwargs = {}
2186 for k, v in kwargs.items():
2187 if isinstance(v, Bag):
2188 bag_kwargs[k] = v
2189 bags.append(v)
2190 else:
2191 other_kwargs[k] = v
2192
2193 other_kwargs, collections = unpack_scalar_dask_kwargs(other_kwargs)
2194 dependencies.extend(collections)
2195
2196 if not bags:
2197 raise ValueError("At least one argument must be a Bag.")
2198
2199 npartitions = {b.npartitions for b in bags}
2200 if len(npartitions) > 1:
2201 raise ValueError("All bags must have the same number of partitions.")
2202 npartitions = npartitions.pop()
2203
2204 def build_iters(n):
2205 args = [(a.name, n) if isinstance(a, Bag) else a for a in args2]
2206 if bag_kwargs:
2207 args.extend((b.name, n) for b in bag_kwargs.values())
2208 return args
2209
2210 if bag_kwargs:
2211 iter_kwarg_keys = list(bag_kwargs)
2212 else:
2213 iter_kwarg_keys = None
2214
2215 dsk = {
2216 (name, n): (
2217 reify,
2218 (map_chunk, func, build_iters(n), iter_kwarg_keys, other_kwargs),
2219 )
2220 for n in range(npartitions)
2221 }
2222
2223 # If all bags are the same type, use that type, otherwise fallback to Bag
2224 return_type = set(map(type, bags))
2225 return_type = return_type.pop() if len(return_type) == 1 else Bag
2226
2227 graph = HighLevelGraph.from_collections(name, dsk, dependencies=bags + dependencies)
2228
2229 return return_type(graph, name, npartitions)
2230
2231
2232 def map_partitions(func, *args, **kwargs):
2233 """Apply a function to every partition across one or more bags.
2234
2235 Note that all ``Bag`` arguments must be partitioned identically.
2236
2237 Parameters
2238 ----------
2239 func : callable
2240 *args, **kwargs : Bag, Item, Delayed, or object
2241 Arguments and keyword arguments to pass to ``func``.
2242
2243 Examples
2244 --------
2245 >>> import dask.bag as db
2246 >>> b = db.from_sequence(range(1, 101), npartitions=10)
2247 >>> def div(nums, den=1):
2248 ... return [num / den for num in nums]
2249
2250 Using a python object:
2251
2252 >>> hi = b.max().compute()
2253 >>> hi
2254 100
2255 >>> b.map_partitions(div, den=hi).take(5)
2256 (0.01, 0.02, 0.03, 0.04, 0.05)
2257
2258 Using an ``Item``:
2259
2260 >>> b.map_partitions(div, den=b.max()).take(5)
2261 (0.01, 0.02, 0.03, 0.04, 0.05)
2262
2263 Note that while both versions give the same output, the second forms a
2264 single graph, and then computes everything at once, and in some cases
2265 may be more efficient.
2266 """
2267 name = kwargs.pop("token", None) or funcname(func)
2268 name = "{}-{}".format(name, tokenize(func, "map-partitions", *args, **kwargs))
2269 bags = []
2270 args2 = []
2271 dependencies = []
2272 for a in args:
2273 if isinstance(a, Bag):
2274 bags.append(a)
2275 args2.append(a)
2276 else:
2277 a, collections = _blockwise_unpack_collections_task_spec(a)
2278 args2.append(a)
2279 dependencies.extend(collections)
2280
2281 bag_kwargs = {}
2282 other_kwargs = {}
2283 for k, v in kwargs.items():
2284 if isinstance(v, Bag):
2285 bag_kwargs[k] = v
2286 bags.append(v)
2287 else:
2288 other_kwargs[k] = v
2289
2290 other_kwargs, collections = unpack_scalar_dask_kwargs(other_kwargs)
2291 dependencies.extend(collections)
2292
2293 if not bags:
2294 raise ValueError("At least one argument must be a Bag.")
2295
2296 npartitions = {b.npartitions for b in bags}
2297 if len(npartitions) > 1:
2298 raise ValueError("All bags must have the same number of partitions.")
2299 npartitions = npartitions.pop()
2300
2301 if bag_kwargs:
2302
2303 def build_args(n):
2304 return [TaskRef((a.name, n)) if isinstance(a, Bag) else a for a in args2]
2305
2306 def build_bag_kwargs(n) -> dict:
2307 if not bag_kwargs:
2308 return other_kwargs
2309 rv = {
2310 k: TaskRef((b.name, n)) if isinstance(b, Bag) else b
2311 for k, b in bag_kwargs.items()
2312 }
2313 rv.update(other_kwargs)
2314 return rv
2315
2316 # Avoid using `blockwise` when a key-word
2317 # argument is being used to refer to a collection.
2318 dsk = {
2319 (name, n): Task(
2320 (name, n),
2321 func,
2322 *build_args(n),
2323 **build_bag_kwargs(n),
2324 )
2325 for n in range(npartitions)
2326 }
2327 else:
2328 pairs = []
2329 numblocks = {}
2330 for arg in args2:
2331 # TODO: Allow interaction with Frame/Array
2332 # collections with proper partitioning
2333 if isinstance(arg, Bag):
2334 pairs.extend([arg.name, "i"])
2335 numblocks[arg.name] = (arg.npartitions,)
2336 else:
2337 pairs.extend([arg, None])
2338 dsk = blockwise(
2339 func,
2340 name,
2341 "i",
2342 *pairs,
2343 numblocks=numblocks,
2344 concatenate=True,
2345 dependencies=dependencies,
2346 **other_kwargs,
2347 )
2348
2349 # If all bags are the same type, use that type, otherwise fallback to Bag
2350 return_type = set(map(type, bags))
2351 return_type = return_type.pop() if len(return_type) == 1 else Bag
2352
2353 graph = HighLevelGraph.from_collections(name, dsk, dependencies=bags + dependencies)
2354
2355 return return_type(graph, name, npartitions)
2356
2357
2358 def _reduce(binop, sequence, initial=no_default):
2359 if initial is not no_default:
2360 return reduce(binop, sequence, initial)
2361 else:
2362 return reduce(binop, sequence)
2363
2364
2365 def make_group(k, stage):
2366 def h(x):
2367 return x[0] // k**stage % k
2368
2369 return h
2370
2371
2372 def groupby_tasks(b, grouper, hash=lambda x: int(tokenize(x), 16), max_branch=32):
2373 max_branch = max_branch or 32
2374 n = b.npartitions
2375
2376 stages = int(math.ceil(math.log(n) / math.log(max_branch))) or 1
2377 if stages > 1:
2378 k = int(math.ceil(n ** (1 / stages)))
2379 else:
2380 k = n
2381
2382 groups = []
2383 splits = []
2384 joins = []
2385
2386 inputs = [tuple(digit(i, j, k) for j in range(stages)) for i in range(k**stages)]
2387
2388 b2 = b.map(partial(chunk.groupby_tasks_group_hash, hash=hash, grouper=grouper))
2389
2390 token = tokenize(b, grouper, hash, max_branch)
2391
2392 shuffle_join_name = "shuffle-join-" + token
2393 shuffle_group_name = "shuffle-group-" + token
2394 shuffle_split_name = "shuffle-split-" + token
2395
2396 start = {}
2397
2398 for idx, inp in enumerate(inputs):
2399 group = {}
2400 split = {}
2401 if idx < b.npartitions:
2402 start[(shuffle_join_name, 0, inp)] = (b2.name, idx)
2403 else:
2404 start[(shuffle_join_name, 0, inp)] = []
2405
2406 for stage in range(1, stages + 1):
2407 _key_tuple = (shuffle_group_name, stage, inp)
2408 group[_key_tuple] = (
2409 groupby,
2410 (make_group, k, stage - 1),
2411 (shuffle_join_name, stage - 1, inp),
2412 )
2413
2414 for i in range(k):
2415 split[(shuffle_split_name, stage, i, inp)] = (
2416 dict.get,
2417 _key_tuple,
2418 i,
2419 {},
2420 )
2421
2422 groups.append(group)
2423 splits.append(split)
2424
2425 for stage in range(1, stages + 1):
2426 join = {
2427 (shuffle_join_name, stage, inp): (
2428 list,
2429 (
2430 toolz.concat,
2431 [
2432 (
2433 shuffle_split_name,
2434 stage,
2435 inp[stage - 1],
2436 insert(inp, stage - 1, j),
2437 )
2438 for j in range(k)
2439 ],
2440 ),
2441 )
2442 for inp in inputs
2443 }
2444
2445 joins.append(join)
2446
2447 name = "shuffle-" + token
2448
2449 end = {
2450 (name, i): (list, (dict.items, (groupby, grouper, (pluck, 1, j))))
2451 for i, j in enumerate(join)
2452 }
2453
2454 groups.extend(splits)
2455 groups.extend(joins)
2456
2457 dsk = merge(start, end, *(groups))
2458 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[b2])
2459 return type(b)(graph, name, len(inputs))
2460
2461
2462 def groupby_disk(b, grouper, npartitions=None, blocksize=2**20):
2463 if npartitions is None:
2464 npartitions = b.npartitions
2465 token = tokenize(b, grouper, npartitions, blocksize)
2466
2467 import partd
2468
2469 p = ("partd-" + token,)
2470 dirname = config.get("temporary_directory", None)
2471 if dirname:
2472 file = (apply, partd.File, (), {"dir": dirname})
2473 else:
2474 file = (partd.File,)
2475 try:
2476 dsk1 = {p: (partd.Python, (partd.Snappy, file))}
2477 except AttributeError:
2478 dsk1 = {p: (partd.Python, file)}
2479
2480 # Partition data on disk
2481 name = f"groupby-part-{funcname(grouper)}-{token}"
2482 dsk2 = {
2483 (name, i): (partition, grouper, (b.name, i), npartitions, p, blocksize)
2484 for i in range(b.npartitions)
2485 }
2486
2487 # Barrier
2488 barrier_token = "groupby-barrier-" + token
2489
2490 dsk3 = {barrier_token: (chunk.barrier,) + tuple(dsk2)}
2491
2492 # Collect groups
2493 name = "groupby-collect-" + token
2494 dsk4 = {
2495 (name, i): (collect, grouper, i, p, barrier_token) for i in range(npartitions)
2496 }
2497
2498 dsk = merge(dsk1, dsk2, dsk3, dsk4)
2499 graph = HighLevelGraph.from_collections(name, dsk, dependencies=[b])
2500 return type(b)(graph, name, npartitions)
2501
2502
2503 def empty_safe_apply(func, part, is_last):
2504 if isinstance(part, Iterator):
2505 try:
2506 _, part = peek(part)
2507 except StopIteration:
2508 if not is_last:
2509 return no_result
2510 return func(part)
2511 elif not is_last and len(part) == 0:
2512 return no_result
2513 else:
2514 return func(part)
2515
2516
2517 def empty_safe_aggregate(func, parts, is_last):
2518 parts2 = (p for p in parts if p is not no_result)
2519 return empty_safe_apply(func, parts2, is_last)
2520
2521
2522 def safe_take(n, b, warn=True):
2523 r = list(take(n, b))
2524 if len(r) != n and warn:
2525 warnings.warn(
2526 f"Insufficient elements for `take`. {n} elements requested, only {len(r)} "
2527 "elements available. Try passing larger `npartitions` to `take`."
2528 )
2529 return r
2530
2531
2532 def random_sample(x, state_data, prob):
2533 """Filter elements of `x` by a probability `prob`.
2534
2535 Parameters
2536 ----------
2537 x : iterable
2538 state_data : tuple
2539 A tuple that can be passed to ``random.Random.setstate``.
2540 prob : float
2541 A float between 0 and 1, representing the probability that each
2542 element will be yielded.
2543 """
2544 random_state = Random()
2545 random_state.setstate(state_data)
2546 for i in x:
2547 if random_state.random() < prob:
2548 yield i
2549
2550
2551 def random_state_data_python(
2552 n: int, random_state: int | Random | None = None
2553 ) -> list[tuple[int, tuple[int, ...], None]]:
2554 """Return a list of tuples that can be passed to
2555 ``random.Random.setstate``.
2556
2557 Parameters
2558 ----------
2559 n : int
2560 Number of tuples to return.
2561 random_state : int or ``random.Random``, optional
2562 If an int, is used to seed a new ``random.Random``.
2563
2564 See Also
2565 --------
2566 dask.utils.random_state_data
2567 """
2568 maxuint32 = 1 << 32
2569
2570 try:
2571 import numpy as np
2572
2573 if isinstance(random_state, Random):
2574 random_state = random_state.randint(0, maxuint32)
2575 np_rng = np.random.default_rng(random_state)
2576
2577 random_data = np_rng.bytes(624 * n * 4) # `n * 624` 32-bit integers
2578 arr = np.frombuffer(random_data, dtype=np.uint32).reshape((n, -1))
2579 return [(3, tuple(row) + (624,), None) for row in arr.tolist()]
2580
2581 except ImportError:
2582 # Pure python (much slower)
2583 if not isinstance(random_state, Random):
2584 random_state = Random(random_state)
2585
2586 return [
2587 (
2588 3,
2589 tuple(random_state.randint(0, maxuint32) for _ in range(624)) + (624,),
2590 None,
2591 )
2592 for _ in range(n)
2593 ]
2594
2595
2596 def split(seq, n):
2597 """Split apart a sequence into n equal pieces.
2598
2599 >>> split(range(10), 3)
2600 [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
2601 """
2602 if not isinstance(seq, (list, tuple)):
2603 seq = list(seq)
2604
2605 part = len(seq) / n
2606 L = [seq[int(part * i) : int(part * (i + 1))] for i in range(n - 1)]
2607 L.append(seq[int(part * (n - 1)) :])
2608 return L
2609
2610
2611 def to_dataframe(seq, columns, dtypes):
2612 import pandas as pd
2613 from packaging.version import Version
2614
2615 seq = reify(seq)
2616 # pd.DataFrame expects lists, only copy if necessary
2617 if not isinstance(seq, list):
2618 seq = list(seq)
2619
2620 kwargs = {} if Version(pd.__version__).major >= 3 else {"copy": False}
2621 res = pd.DataFrame(seq, columns=list(columns))
2622 return res.astype(dtypes, **kwargs)
2623
2624
2625 def repartition_npartitions(bag, npartitions):
2626 """Changes the number of partitions of the bag.
2627
2628 This can be used to reduce or increase the number of partitions
2629 of the bag.
2630 """
2631 if npartitions == bag.npartitions:
2632 return bag
2633
2634 new_name = "repartition-%d-%s" % (npartitions, tokenize(bag, npartitions))
2635 if bag.npartitions > npartitions:
2636 ratio = bag.npartitions / npartitions
2637 new_partitions_boundaries = [
2638 int(old_partition_index * ratio)
2639 for old_partition_index in range(npartitions + 1)
2640 ]
2641 return _repartition_from_boundaries(bag, new_partitions_boundaries, new_name)
2642 else: # npartitions > bag.npartitions
2643 div, mod = divmod(npartitions, bag.npartitions)
2644 nsplits = [div] * bag.npartitions
2645 nsplits[-1] += mod
2646 return _split_partitions(bag, nsplits, new_name)
2647
2648
2649 def total_mem_usage(partition):
•2650 # Reify iterables to measure actual memory size.
2651 # Each compute creates a fresh iterator from the graph.
2652 if isinstance(partition, Iterable):
•2653 partition = reify(partition)
2654 return sizeof(partition)
2655
2656
2657 def repartition_size(bag, size):
2658 """
2659 Repartition bag so that new partitions have approximately `size` memory usage each
2660 """
2661 if isinstance(size, str):
2662 size = parse_bytes(size)
2663 size = int(size)
2664 mem_usages = bag.map_partitions(total_mem_usage).compute()
2665
2666 # 1. split each partition that is larger than partition size
2667 nsplits = [1 + mem_usage // size for mem_usage in mem_usages]
2668 if any(nsplit > 1 for nsplit in nsplits):
2669 split_name = f"repartition-split-{tokenize(bag, size)}"
2670 bag = _split_partitions(bag, nsplits, split_name)
2671 # update mem_usages to account for the split partitions
2672 split_mem_usages = []
2673 for n, usage in zip(nsplits, mem_usages):
2674 split_mem_usages.extend([usage / n] * n)
2675 mem_usages = split_mem_usages
2676
2677 # 2. now that all partitions are less than size, concat them up to size
2678 assert all(mem_usage <= size for mem_usage in mem_usages)
2679 new_npartitions = list(map(len, iter_chunks(mem_usages, size)))
2680 new_partitions_boundaries = accumulate(operator.add, new_npartitions)
2681 new_name = f"repartition-{tokenize(bag, size)}"
2682 return _repartition_from_boundaries(bag, new_partitions_boundaries, new_name)
2683
2684
2685 def _split_partitions(bag, nsplits, new_name):
2686 """Split a Dask bag into new partitions
2687
2688 Parameters
2689 ----------
2690 bag: Dask bag
2691 nsplits: List[int]
2692 Number of target bags for each partition
2693 The length of nsplits should be the same as bag.npartitions
2694 new_name: str
2695
2696 See Also
2697 --------
2698 repartition_npartitions
2699 repartition_size
2700 """
2701 if len(nsplits) != bag.npartitions:
2702 raise ValueError(f"nsplits should have len={bag.npartitions}")
2703 dsk = {}
2704 split_name = f"split-{tokenize(bag, nsplits)}"
2705 j = 0
2706 for i, k in enumerate(nsplits):
2707 if k == 1:
2708 dsk[new_name, j] = (bag.name, i)
2709 j += 1
2710 else:
2711 dsk[split_name, i] = (split, (bag.name, i), k)
2712 for jj in range(k):
2713 dsk[new_name, j] = (operator.getitem, (split_name, i), jj)
2714 j += 1
2715
2716 graph = HighLevelGraph.from_collections(new_name, dsk, dependencies=[bag])
2717 return Bag(graph, name=new_name, npartitions=sum(nsplits))
2718
2719
2720 def _repartition_from_boundaries(bag, new_partitions_boundaries, new_name):
2721 if not isinstance(new_partitions_boundaries, list):
2722 new_partitions_boundaries = list(new_partitions_boundaries)
2723 if new_partitions_boundaries[0] > 0:
2724 new_partitions_boundaries.insert(0, 0)
2725 if new_partitions_boundaries[-1] < bag.npartitions:
2726 new_partitions_boundaries.append(bag.npartitions)
2727 num_new_partitions = len(new_partitions_boundaries) - 1
2728 dsk = {}
2729 for new_partition_index in range(num_new_partitions):
2730 value = (
2731 list,
2732 (
2733 toolz.concat,
2734 [
2735 (bag.name, old_partition_index)
2736 for old_partition_index in range(
2737 new_partitions_boundaries[new_partition_index],
2738 new_partitions_boundaries[new_partition_index + 1],
2739 )
2740 ],
2741 ),
2742 )
2743 dsk[new_name, new_partition_index] = value
2744 graph = HighLevelGraph.from_collections(new_name, dsk, dependencies=[bag])
2745 return Bag(graph, name=new_name, npartitions=num_new_partitions)