Debian Codegraph @

docs/source/dataframe-best-practices.rst

raw
1 .. _dataframe.performance:
2
3 Dask DataFrames Best Practices
4 ==============================
5
6 .. meta::
7 :description: Suggestions for Dask DataFrames best practices and solutions to common problems.
8
9 It is easy to get started with Dask DataFrame, but using it *well* does require
10 some experience. This page contains suggestions for Dask DataFrames best practices,
11 and includes solutions to common problems.
12
13 Use Pandas
14 ----------
15
16 For data that fits into RAM, pandas can often be faster and easier to use than
17 Dask DataFrame. While "Big Data" tools can be exciting, they are almost always
18 worse than normal data tools while those remain appropriate.
19
20
21 Reduce, and then use pandas
22 ---------------------------
23
24 Similar to above, even if you have a large dataset there may be a point in your
25 computation where you've reduced things to a more manageable level. You may
26 want to switch to pandas at this point.
27
28 .. code-block:: python
29
30 df = dd.read_parquet('my-giant-file.parquet')
31 df = df[df.name == 'Alice'] # Select a subsection
32 result = df.groupby('id').value.mean() # Reduce to a smaller size
33 result = result.compute() # Convert to pandas dataframe
34 result... # Continue working with pandas
35
36 Pandas Performance Tips Apply to Dask DataFrame
37 -----------------------------------------------
38
39 Usual pandas performance tips like avoiding apply, using vectorized
40 operations, using categoricals, etc., all apply equally to Dask DataFrame. See
41 `Modern Pandas <https://tomaugspurger.github.io/modern-1-intro>`_ by `Tom
42 Augspurger <https://github.com/TomAugspurger>`_ for a good read on this topic.
43
44 Use the Index
45 -------------
46
47 Dask DataFrame can be optionally sorted along a single index column. Some
48 operations against this column can be very fast. For example, if your dataset
49 is sorted by time, you can quickly select data for a particular day, perform
50 time series joins, etc. You can check if your data is sorted by looking at the
51 ``df.known_divisions`` attribute. You can set an index column using the
52 ``.set_index(column_name)`` method. This operation is expensive though, so use
53 it sparingly (see below):
54
55 .. code-block:: python
56
57 df = df.set_index('timestamp') # set the index to make some operations fast
58
59 df.loc['2001-01-05':'2001-01-12'] # this is very fast if you have an index
60 df.merge(df2, left_index=True, right_index=True) # this is also very fast
61
62 For more information, see documentation on :ref:`dataframe partitions <dataframe-design-partitions>`.
63
64 Avoid Full-Data Shuffling
65 -------------------------
66
67 Setting an index is an important but expensive operation (see above). You
68 should do it infrequently and you should persist afterwards (see below).
69
70 Some operations like ``set_index`` and ``merge/join`` are harder to do in a
71 parallel or distributed setting than if they are in-memory on a single machine.
72 In particular, *shuffling operations* that rearrange data become much more
73 communication intensive. For example, if your data is arranged by customer ID
74 but now you want to arrange it by time, all of your partitions will have to talk
75 to each other to exchange shards of data. This can be an intensive process,
76 particularly on a cluster.
77
78 So, definitely set the index but try do so infrequently.
79
80 .. code-block:: python
81
82 df = df.set_index('column_name') # do this infrequently
83
84 Additionally, ``set_index`` has a few options that can accelerate it in some
85 situations. For example, if you know that your dataset is sorted or you already
86 know the values by which it is divided, you can provide these to accelerate the
87 ``set_index`` operation. For more information, see the `set_index docstring
88 <https://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.set_index>`_.
89
90 .. code-block:: python
91
92 df2 = df.set_index(d.timestamp, sorted=True)
93
94
95 Persist Intelligently
96 ---------------------
97
98 .. note:: This section is only relevant to users on distributed systems.
99
100 .. warning::
101
102 persist has a number of drawbacks with the query optimizer. It will block all
103 optimizations and prevent us from pushing column projections or filters into
104 the IO layer. Use persist sparingly only when absolutely necessary or you need
105 the full dataset afterwards.
106
107 Often DataFrame workloads look like the following:
108
109 1. Load data from files
110 2. Filter data to a particular subset
111 3. Shuffle data to set an intelligent index
112 4. Several complex queries on top of this indexed data
113
114 It is often ideal to load, filter, and shuffle data once and keep this result in
115 memory. Afterwards, each of the several complex queries can be based off of
116 this in-memory data rather than have to repeat the full load-filter-shuffle
117 process each time. To do this, use the `client.persist
118 <https://distributed.dask.org/en/latest/api.html#distributed.Client.persist>`_
119 method:
120
121 .. code-block:: python
122
123 df = dd.read_csv('s3://bucket/path/to/*.csv')
124 df = df[df.balance < 0]
125 df = client.persist(df)
126
127 df = df.set_index('timestamp')
128 df = client.persist(df)
129
130 >>> df.customer_id.nunique().compute()
131 18452844
132
133 >>> df.groupby(df.city).size().compute()
134 ...
135
136 Persist is important because Dask DataFrame is *lazy by default*. It is a
137 way of telling the cluster that it should start executing the computations
138 that you have defined so far, and that it should try to keep those results in
139 memory. You will get back a new DataFrame that is semantically equivalent to
140 your old DataFrame, but now points to running data. Your old DataFrame still
141 points to lazy computations:
142
143 .. code-block:: python
144
145 # Don't do this
146 client.persist(df) # persist doesn't change the input in-place
147
148 # Do this instead
149 df = client.persist(df) # replace your old lazy DataFrame
150
151
152 Repartition to Reduce Overhead
153 ------------------------------
154
155 Your Dask DataFrame is split up into many pandas DataFrames. We sometimes call
156 these "partitions", and often the number of partitions is decided for you. For
157 example, it might be the number of CSV files from which you are reading. However,
158 over time, as you reduce or increase the size of your pandas DataFrames by
159 filtering or joining, it may be wise to reconsider how many partitions you need.
160 There is a cost to having too many or having too few.
161
162 .. image:: images/dask-dataframe.svg
163 :alt: Individual partitions of a Dask DataFrame are pandas DataFrames. One tip from Dask DataFrames Best Practices is to repartition these partitions.
164 :width: 45%
165 :align: right
166
167 Partitions should fit comfortably in memory (smaller than a gigabyte) but also
168 not be too many. Every operation on every partition takes the central
169 scheduler a few hundred microseconds to process. If you have a few thousand
170 tasks this is barely noticeable, but it is nice to reduce the number if
171 possible.
172
173 A common situation is that you load lots of data into reasonably sized
174 partitions (Dask's defaults make decent choices), but then you filter down your
175 dataset to only a small fraction of the original. At this point, it is wise to
176 regroup your many small partitions into a few larger ones. You can do this by
177 using the :py:class:`dask.dataframe.DataFrame.repartition` method:
178
179 .. code-block:: python
180
181 df = dd.read_csv('s3://bucket/path/to/*.csv')
182 df = df[df.name == 'Alice'] # only 1/100th of the data
183 df = df.repartition(npartitions=df.npartitions // 100)
184
185 df = df.persist() # if on a distributed system
186
187 This helps to reduce overhead and increase the effectiveness of vectorized
188 Pandas operations. You should aim for partitions that have around 100MB of
189 data each.
190
191 Joins
192 -----
193
194 Joining two DataFrames can be either very expensive or very cheap depending on
195 the situation. It is cheap in the following cases:
196
197 1. Joining a Dask DataFrame with a pandas DataFrame
198 2. Joining a Dask DataFrame with another Dask DataFrame of a single partition
199 3. Joining Dask DataFrames along their indexes
200
201 And expensive in the following case:
202
203 1. Joining Dask DataFrames along columns that are not their index
204
205 The expensive case requires a shuffle. This is fine, and Dask DataFrame will
206 complete the job well, but it will be more expensive than a typical linear-time
207 operation:
208
209 .. code-block:: python
210
211 dd.merge(a, pandas_df) # fast
212 dd.merge(a, b, left_index=True, right_index=True) # fast
213 dd.merge(a, b, left_index=True, right_on='id') # half-fast, half-slow
214 dd.merge(a, b, left_on='id', right_on='id') # slow
215
216 For more information see :doc:`Joins <dataframe-joins>`.
217
218 Use Parquet
219 -----------
220
221 `Apache Parquet <https://parquet.apache.org/>`_ is a columnar binary format.
222 It is the de-facto standard for the storage of large volumes of tabular data
223 and our recommended storage solution for basic tabular data.
224
225 .. code-block:: python
226
227 df.to_parquet('path/to/my-results/')
228 df = dd.read_parquet('path/to/my-results/')
229
230 When compared to formats like CSV, Parquet brings the following advantages:
231
232 1. It's faster to read and write, often by 4-10x
233 2. It's more compact to store, often by 2-5x
234 3. It has a schema, and so there's no ambiguity about what types the columns are. This avoids confusing errors.
235 4. It supports more advanced data types, like categoricals, proper datetimes, and more
236 5. It's more portable, and can be used with other systems like databases or Apache Spark
237 6. Depending on how the data is partitioned Dask can identify sorted columns, and sometimes pick out subsets of data more efficiently
238
239 See :ref:`dataframe.parquet` for more details.