Skip to content

Different categories in different partitions #1836

Closed

Description

@mrocklin

Categoricals are currently difficult in dask.dataframe because all partitions must have the same set of categories. This synchronization can be very expensive, often requiring full table scans. Operations like .astype('category') or read_csv(..., dtypes={'x': 'category'}) don't work as expected.

Recently pandas started to support union-ing categoricals on concatenation. This ability might allow dask.dataframe to instead maintain categories per-partition, which removes the burden of synchronization. We would only combine categoricals when different partitions need to interact. This would help us in data loading (csv, parquet) and in aggregations (groupbys, etc.) but not for operations like pivot_table which expect to know the categories ahead of time.

This might be as easy as adding the right call to union_categoricals in dask.dataframe.core._concat, but there are probably other nuances.

What is the best way to do this?

cc @TomAugspurger @martindurant @sinhrks

Activity

  1. martindurant commented on Dec 8, 2016

    @martindurant
    Member

    Quick note: getting the full set of categories is very fast if the data is in memory (df.col.cat.categories as opposed to unique).
    Also, specifically for parquet: if the data was written by fastparquet (via dask or not), then we can guarantee that the categories will be the same for each chunk.

  2. mrocklin commented on Dec 8, 2016

    @mrocklin
    MemberAuthor

    If we remove the requirement that Dask.dataframe partitions all agree on categories then we might want to change the dask.dataframe parquet writer so that it writes individual partitions without synchronizing categories beforehand.

  3. TomAugspurger commented on Dec 12, 2016

    @TomAugspurger
    Member

    I think this is a good idea... This should be transparent to the user, correct? It'll be up to dask to know when to union categoricals in the background?

    Operations like .astype('category') or read_csv(..., dtypes={'x': 'category'}) don't work as expected.

    This should be less painful once I finish the CategoricalDtype refactoring in pandas, for the cases where you know the set of categories ahead of time. The proposal here would still be useful for the unknown categories case.

  4. martindurant commented on Dec 12, 2016

    @martindurant
    Member

    "CategoricalDtype refactoring" - is there a link for this?

  5. TomAugspurger commented on Dec 12, 2016

    @TomAugspurger
    Member

    @martindurant pandas-dev/pandas#14711

    short version: move categories and ordered into the dtype itself. Then add that to the public API and let users say pd.read_csv('...', dtype={'a': pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)}). Should be entirely backwards compatible.

  6. mrocklin commented on Dec 12, 2016

    @mrocklin
    MemberAuthor

    @TomAugspurger can you help me create a list of operations that this change will affect?

    Operations that become harder

    • pivot_table
    • df.x.cat.codes
    • df.x.cat.categories

    Operations that requires intelligent merging

    • Anything relying on apply-concat-apply (groupby-aggregations, reductions, drop_duplicates, etc.)
    • merge?
    • groupby-apply?

    What is the right way to merge two dataframes with categories?

    In [1]: import pandas as pd
    
    In [2]: a = pd.DataFrame({'x': [1, 2, 3], 'y': ['a', 'b', 'a']})
    
    In [3]: b = pd.DataFrame({'x': [4, 5, 6], 'y': ['a', 'c', 'c']})
    
    In [4]: a['y'] = a.y.astype('category')
    
    In [5]: b['y'] = b.y.astype('category')
    
    In [6]: c = ... # concatenate a and b, respecting categories
    
  7. martindurant commented on Dec 12, 2016

    @martindurant
    Member

    http://pandas.pydata.org/pandas-docs/stable/categorical.html#unioning
    The function, not yet in concat, is

    In []: union_categoricals([a['y'], b['y']])
    Out[]:
    [a, b, a, a, c, c]
    Categories (3, object): [a, b, c]
    

    (series by series)

  8. mrocklin commented on Jan 23, 2017

    @mrocklin
    MemberAuthor

    @martindurant this change might affect dask's parquet reading and writing, which no longer needs to have a consistent set of categories in the metadata of all partitions.

  9. martindurant commented on Jan 23, 2017

    @martindurant
    Member

    Writing will not be affected, since each partition is treated separately.
    On reading, this should actually simplify things a bit, I think. Am I right in thinking that the change here just means that the labels are not the same everywhere, but we do guarantee that the given column is categorical everywhere?

  10. mrocklin commented on Jan 23, 2017

    @mrocklin
    MemberAuthor

    Am I right in thinking that the change here just means that the labels are not the same everywhere, but we do guarantee that the given column is categorical everywhere?

    Correct

  11. martindurant commented on Jan 23, 2017

    @martindurant
    Member

    I have a good feeling that removing L80-84, 123-124 in dask.io.parquet will do the right thing. I'll test that (and make a specific test) when I get to it.
    Does the metadata now not need to know about category labels at all?

  12. mrocklin commented on Jan 23, 2017

    @mrocklin
    MemberAuthor

    I believe that @jcrist established a convention around what to specify if categories are unknown.

  13. jcrist commented on Jan 23, 2017

    @jcrist
    Member

    Unknown categoricals should include dd.utils.UNKNOWN_CATEGORIES in their categories. You could either build each categorical yourself, or use dd.utils.clear_known_categories, which can be used to set known categorical columns to unknown.

  14. martindurant commented on Jan 23, 2017

    @martindurant
    Member

    The writing and reading seem to magically just work right now, although the lines above cause an unnecessary preemptive read.
    I realise, though, that reading categoricals in fastparquet itself does require the same labels in every row-group, which I think is documented, but may be surprising.

  15. mrocklin commented on Jan 23, 2017

    @mrocklin
    MemberAuthor

    Here is a fail case:

    In [1]: import pandas as pd
    In [2]: import dask.dataframe as dd
    
    In [3]: df = pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y': list('caaab')})
    
    In [4]: ddf = dd.from_pandas(df, npartitions=2)
    
    In [5]: ddf['y'] = ddf.y.astype('category')
    
    In [6]: ddf.y.cat.categories
    ---------------------------------------------------------------------------
    NotImplementedError                       Traceback (most recent call last)
    <ipython-input-6-5e223c5a5c45> in <module>()
    ----> 1 ddf.y.cat.categories
    
    /home/mrocklin/workspace/dask/dask/dataframe/categorical.py in categories(self)
        159                    "supported.  Please use `column.cat.as_known()` or "
        160                    "`df.categorize()` beforehand to ensure known categories")
    --> 161             raise NotImplementedError(msg)
        162         return self._delegate_property(self._series._meta, 'cat', 'categories')
        163 
    
    NotImplementedError: `df.column.cat.categories` with unknown categories is not supported.  Please use `column.cat.as_known()` or `df.categorize()` beforehand to ensure known categories
    
    In [7]: ddf.to_parquet('foo')
    
    In [8]: ddf2 = dd.read_parquet('foo', categories=['y'])
    
    In [9]: ddf2.y.cat.categories
    Out[9]: Index(['a', 'c'], dtype='object')
    
    In [10]: ddf2.y.compute().cat.categories
    Out[10]: Index(['a', 'c', 'b'], dtype='object')

    I suggest that we don't use the categories of the first partition in read_parquet, but instead use the unknown categories convention.

  16. martindurant commented on Jan 23, 2017

    @martindurant
    Member

    OK, so read_parquet should call dd.utils.clear_known_categories, and then will have the same behaviour.

  17. mrocklin commented on Jan 23, 2017

    @mrocklin
    MemberAuthor

    In these lines:

        for cat in categories:
            meta[cat] = pd.Series(pd.Categorical([], categories=cats[cat]))

    We probably need to replace cats[cat] with [dd.utils.UNKNOWN_CATEGORIES].

  18. added this to the 0.14.0 milestone on Mar 4, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions