Debian Codegraph @

docs/source/dataframe-groupby.rst

raw
1 Shuffling Performance
2 =====================
3
4 .. currentmodule:: dask.dataframe
5
6 Operations like ``groupby``, ``join``, and ``set_index`` have special
7 performance considerations that are different from normal Pandas due to the
8 parallel, larger-than-memory, and distributed nature of Dask DataFrame.
9
10 Easy Case
11 ---------
12
13 To start off, common groupby operations like
14 ``df.groupby(columns).reduction()`` for known reductions like ``mean, sum, std,
15 var, count, nunique`` are all quite fast and efficient, even if partitions are
16 not cleanly divided with known divisions. This is the common case.
17
18 Additionally, if divisions are known, then applying an arbitrary function to
19 groups is efficient when the grouping columns include the index.
20
21 Joins are also quite fast when joining a Dask DataFrame to a Pandas DataFrame
22 or when joining two Dask DataFrames along their index. No special
23 considerations need to be made when operating in these common cases.
24
25 So, if you're doing common groupby and join operations, then you can stop reading
26 this. Everything will scale nicely. Fortunately, this is true most of the
27 time:
28
29 .. code-block:: python
30
31 >>> ddf.groupby(columns).known_reduction() # Fast and common case
32 >>> ddf.groupby(columns_with_index).apply(user_fn) # Fast and common case
33 >>> ddf.join(pandas_df, on=column) # Fast and common case
34 >>> lhs.join(rhs) # Fast and common case
35 >>> lhs.merge(rhs, on=columns_with_index) # Fast and common case
36
37 Difficult Cases
38 ---------------
39
40 In some cases, such as when applying an arbitrary function to groups (when not
41 grouping on index with known divisions), when joining along non-index columns,
42 or when explicitly setting an unsorted column to be the index, we may need to
43 trigger a full dataset shuffle:
44
45 .. code-block:: python
46
47 >>> ddf.groupby(columns_no_index).apply(user_fn) # Requires shuffle
48 >>> lhs.join(rhs, on=columns_no_index) # Requires shuffle
49 >>> ddf.set_index(column) # Requires shuffle
50
51 A shuffle is necessary when we need to re-sort our data along a new index. For
52 example, if we have banking records that are organized by time and we now want
53 to organize them by user ID, then we'll need to move a lot of data around. In
54 Pandas all of this data fits in memory, so this operation was easy. Now that we
55 don't assume that all data fits in memory, we must be a bit more careful.
56
57 Re-sorting the data can be avoided by restricting yourself to the easy cases
58 mentioned above.
59
60
61 .. _shuffle-methods:
62
63 Shuffle Methods
64 ---------------
65
66 There are currently two strategies to shuffle data depending on whether you are
67 on a single machine or on a distributed cluster: shuffle on disk and shuffle
68 over the network.
69
70 Shuffle on Disk
71 ```````````````
72
73 When operating on larger-than-memory data on a single machine, we shuffle by
74 dumping intermediate results to disk. This is done using the partd_ project
75 for on-disk shuffles.
76
77 .. _partd: https://github.com/dask/partd
78
79 Shuffle over the Network
80 ````````````````````````
81
82 When operating on a distributed cluster, the Dask workers may not have access to
83 a shared hard drive. In this case, we shuffle data by breaking input partitions
84 into many pieces based on where they will end up and moving these pieces
85 throughout the network.
86
87 Selecting methods
88 `````````````````
89
90 Dask will use on-disk shuffling by default, but will switch to a
91 distributed shuffling algorithm if the default scheduler is set to use a
92 ``dask.distributed.Client``, such as would be the case if the user sets the
93 Client as default:
94
95 .. code-block:: python
96
97 client = Client('scheduler:8786', set_as_default=True)
98
99 Alternatively, if you prefer to avoid defaults, you can configure the global
100 shuffling method with the ``dataframe.shuffle.method`` configuration option.
101 This can be done globally:
102
103 .. code-block:: python
104
105 dask.config.set({"dataframe.shuffle.method": "p2p"})
106
107 ddf.groupby(...).apply(...)
108
109 or as a context manager:
110
111 .. code-block:: python
112
113 with dask.config.set({"dataframe.shuffle.method": "p2p"}):
114 ddf.groupby(...).apply(...)
115
116
117 In addition, ``set_index`` also accepts a ``shuffle_method`` keyword argument that
118 can be used to select either on-disk or task-based shuffling:
119
120 .. code-block:: python
121
122 ddf.set_index(column, shuffle_method='disk')
123 ddf.set_index(column, shuffle_method='tasks')
124 ddf.set_index(column, shuffle_method='p2p')
125
126
127 .. _dataframe.groupby.aggregate:
128
129 Aggregate
130 =========
131
132 Dask supports Pandas' ``aggregate`` syntax to run multiple reductions on the
133 same groups. Common reductions such as ``max``, ``sum``, ``list`` and ``mean`` are
134 directly supported:
135
136 .. code-block:: python
137
138 >>> ddf.groupby(columns).aggregate(['sum', 'mean', 'max', 'min', list])
139
140 Dask also supports user defined reductions. To ensure proper performance, the
141 reduction has to be formulated in terms of three independent steps. The
142 ``chunk`` step is applied to each partition independently and reduces the data
143 within a partition. The ``aggregate`` combines the within partition results.
144 The optional ``finalize`` step combines the results returned from the
145 ``aggregate`` step and should return a single final column. For Dask to
146 recognize the reduction, it has to be passed as an instance of
147 ``dask.dataframe.Aggregation``.
148
149 For example, ``sum`` could be implemented as:
150
151 .. code-block:: python
152
153 custom_sum = dd.Aggregation('custom_sum', lambda s: s.sum(), lambda s0: s0.sum())
154 ddf.groupby('g').agg(custom_sum)
155
156 The name argument should be different from existing reductions to avoid data
157 corruption. The arguments to each function are pre-grouped series objects,
158 similar to ``df.groupby('g')['value']``.
159
160 Many reductions can only be implemented with multiple temporaries. To implement
161 these reductions, the steps should return tuples and expect multiple arguments.
162 A mean function can be implemented as:
163
164 .. code-block:: python
165
166 custom_mean = dd.Aggregation(
167 'custom_mean',
168 lambda s: (s.count(), s.sum()),
169 lambda count, sum: (count.sum(), sum.sum()),
170 lambda count, sum: sum / count,
171 )
172 ddf.groupby('g').agg(custom_mean)
173
174
175 For example, let's compute the group-wise extent (maximum - minimum)
176 for a DataFrame.
177
178 .. code-block:: python
179
180 >>> df = pd.DataFrame({
181 ... 'a': ['a', 'b', 'a', 'a', 'b'],
182 ... 'b': [0, 1, 0, 2, 5],
183 ... })
184 >>> ddf = dd.from_pandas(df, 2)
185
186 We define the building blocks to find the maximum and minimum of each chunk, and then
187 the maximum and minimum over all the chunks. We finalize by taking the difference between
188 the Series with the maxima and minima
189
190 .. code-block:: python
191
192 >>> def chunk(grouped):
193 ... return grouped.max(), grouped.min()
194
195 >>> def agg(chunk_maxes, chunk_mins):
196 ... return chunk_maxes.max(), chunk_mins.min()
197
198 >>> def finalize(maxima, minima):
199 ... return maxima - minima
200
201 Finally, we create and use the aggregation
202
203 .. code-block:: python
204
205 >>> extent = dd.Aggregation('extent', chunk, agg, finalize=finalize)
206 >>> ddf.groupby('a').agg(extent).compute()
207 b
208 a
209 a 2
210 b 4
211
212 To apply :py:class:`dask.dataframe.groupby.SeriesGroupBy.nunique` to more than one
213 column you can use:
214
215 .. code-block:: python
216
217 >>> df['c'] = [1, 2, 1, 1, 2]
218 >>> ddf = dd.from_pandas(df, 2)
219 >>> nunique = dd.Aggregation(
220 ... name="nunique",
221 ... chunk=lambda s: s.apply(lambda x: list(set(x))),
222 ... agg=lambda s0: s0.obj.groupby(level=list(range(s0.obj.index.nlevels))).sum(),
223 ... finalize=lambda s1: s1.apply(lambda final: len(set(final))),
224 ... )
225 >>> ddf.groupby('a').agg({'b':nunique, 'c':nunique})
226
227 To access NumPy functions use ``apply`` with a lambda function such as ``.apply(lambda r: np.sum(r))``. Here's an example of how a sum of squares aggregation would look like:
228
229 .. code-block:: python
230
231 >>> dd.Aggregation(name="sum_of_squares", chunk=lambda s: s.apply(lambda r: np.sum(np.power(r, 2))), agg=lambda s: s.sum())