Debian Codegraph @

docs/source/dataframe-categoricals.rst

raw
1 Categoricals
2 ============
3
4 Dask DataFrame divides `categorical data`_ into two types:
5
6 - Known categoricals have the ``categories`` known statically (on the ``_meta``
7 attribute). Each partition **must** have the same categories as found on the
8 ``_meta`` attribute
9 - Unknown categoricals don't know the categories statically, and may have
10 different categories in each partition. Internally, unknown categoricals are
11 indicated by the presence of ``dd.utils.UNKNOWN_CATEGORIES`` in the
12 categories on the ``_meta`` attribute. Since most DataFrame operations
13 propagate the categories, the known/unknown status should propagate through
14 operations (similar to how ``NaN`` propagates)
15
16 For metadata specified as a description (option 2 above), unknown categoricals
17 are created.
18
19 Certain operations are only available for known categoricals. For example,
20 ``df.col.cat.categories`` would only work if ``df.col`` has known categories,
21 since the categorical mapping is only known statically on the metadata of known
22 categoricals.
23
24 The known/unknown status for a categorical column can be found using the
25 ``known`` property on the categorical accessor:
26
27 .. code-block:: python
28
29 >>> ddf.col.cat.known
30 False
31
32 Additionally, an unknown categorical can be converted to known using
33 ``.cat.as_known()``. If you have multiple categorical columns in a DataFrame,
34 you may instead want to use ``df.categorize(columns=...)``, which will convert
35 all specified columns to known categoricals. Since getting the categories
36 requires a full scan of the data, using ``df.categorize()`` is more efficient
37 than calling ``.cat.as_known()`` for each column (which would result in
38 multiple scans):
39
40 .. code-block:: python
41
42 >>> col_known = ddf.col.cat.as_known() # use for single column
43 >>> col_known.cat.known
44 True
45 >>> ddf_known = ddf.categorize() # use for multiple columns
46 >>> ddf_known.col.cat.known
47 True
48
49 To convert a known categorical to an unknown categorical, there is also the
50 ``.cat.as_unknown()`` method. This requires no computation as it's just a
51 change in the metadata.
52
53 Non-categorical columns can be converted to categoricals in a few different
54 ways:
55
56 .. code-block:: python
57
58 # astype operates lazily, and results in unknown categoricals
59 ddf = ddf.astype({'mycol': 'category', ...})
60 # or
61 ddf['mycol'] = ddf.mycol.astype('category')
62
63 # categorize requires computation, and results in known categoricals
64 ddf = ddf.categorize(columns=['mycol', ...])
65
66 Additionally, with Pandas 0.19.2 and up, ``dd.read_csv`` and ``dd.read_table``
67 can read data directly into unknown categorical columns by specifying a column
68 dtype as ``'category'``:
69
70 .. code-block:: python
71
72 >>> ddf = dd.read_csv(..., dtype={col_name: 'category'})
73
74 .. _`categorical data`: https://pandas.pydata.org/pandas-docs/stable/categorical.html
75
76 Moreover, with Pandas 0.21.0 and up, ``dd.read_csv`` and ``dd.read_table`` can read
77 data directly into *known* categoricals by specifying instances of
78 ``pd.api.types.CategoricalDtype``:
79
80 .. code-block:: python
81
82 >>> dtype = {'col': pd.api.types.CategoricalDtype(['a', 'b', 'c'])}
83 >>> ddf = dd.read_csv(..., dtype=dtype)
84
85 If you write and read to parquet, Dask will forget known categories.
86 This happens because, due to performance concerns, all the categories are
87 saved in every partition rather than in the parquet metadata.
88 It is possible to manually load the categories:
89
90 .. code-block:: python
91
92 >>> import dask.dataframe as dd
93 >>> import pandas as pd
94 >>> df = pd.DataFrame(data=list('abcaabbcc'), columns=['col'])
95 >>> df.col = df.col.astype('category')
96 >>> ddf = dd.from_pandas(df, npartitions=1)
97 >>> ddf.col.cat.known
98 True
99 >>> ddf.to_parquet('tmp')
100 >>> ddf2 = dd.read_parquet('tmp')
101 >>> ddf2.col.cat.known
102 False
103 >>> ddf2.col = ddf2.col.cat.set_categories(ddf2.col.head(1).cat.categories)
104 >>> ddf2.col.cat.known
105 True