Dask Dataframes coordinate many Pandas dataframes, partitioned along an index. They support a large subset of the Pandas API.
Starting the Dask Client is optional. It will provide a dashboard which is useful to gain insight on the computation.
The link to the dashboard will become visible when you create the client below. We recommend having it open on one side of your screen while using your notebook on the other side. This can take some effort to arrange your windows, but seeing them both at the same is very useful when learning.
from dask.distributed import Client, progress client = Client(n_workers=2, threads_per_worker=2, memory_limit='1GB') client
We create a random timeseries of data with the following attributes:
This is a small dataset of about 240 MB. Increase the number of days or reduce the frequency to practice with a larger dataset.
import dask import dask.dataframe as dd df = dask.datasets.timeseries()
Unlike Pandas, Dask DataFrames are lazy and so no data is printed here.
But the column names and dtypes are known.
Some operations will automatically display the data.
import pandas as pd pd.options.display.precision = 2 pd.options.display.max_rows = 10
df2 = df[df.y > 0] df3 = df2.groupby('name').x.std() df3
.compute() when you want your result as a Pandas dataframe.
If you started
Client() above then you may want to watch the status page during computation.
computed_df = df3.compute() type(computed_df)
If you have the available RAM for your dataset then you can persist data in memory.
This allows future computations to be much faster.
df = df.persist()
Random access is cheap along the index, but must still be computed.
Data is sorted by the index column. This allows for faster access, joins, groupby-apply operations, etc.. However sorting data can be costly to do in parallel, so setting the index is both important to do, but only infrequently.
df = df.set_index('name') df
Because computing this dataset is expensive and we can fit it in our available RAM, we persist the dataset to memory.
df = df.persist()
Dask now knows where all data lives, indexed cleanly by name. As a result oerations like random access are cheap and efficient
Now that our data is sorted by name we can easily do operations like random access on name, or groupby-apply with custom functions.
Here we train a different Scikit-Learn linear regression model on each name.
from sklearn.linear_model import LinearRegression def train(partition): est = LinearRegression() est.fit(partition[['x']].values, partition.y.values) return est