Skip to content

[upstream/build] Groupby mean result index doesn't preserve bool dtype #8722

Closed

Description

@phobson

What happened:

@ncclementi and I were tracking down this error on her fork with upstream dependencies:
https://github.com/ncclementi/dask/runs/5148303425?check_suite_focus=true#step:5:11490

Following a recent pandas bug enhancement (pandas-dev/pandas#45061), groupby results with bool-typed indexes are better respected. In dask, the index type generally remains bool, but groupby.mean() returns a dataframe with an object-dtyped index.

If you look at the example below, most operations return a bool index. Mean returns an object index. Interestingly, doing mathematical operations with two dataframes with bool-typed indexes returns a dataframe with an object-typed index

cc: @jrbourbeau
We were not able to track down where the fix for this would occur and need some guidance.

What you expected to happen:

Groupby.mean should preserve the index dtypes, which in turn will allow the tests to pass

Minimal Complete Verifiable Example:

import pandas as pd
import dask.dataframe as dd

pdf = pd.DataFrame(
            {"a": [1, 2, 6, 4, 4, 6, 4, 3, 7], "b": [4, 2, 7, 3, 3, 1, 1, 1, 2]},
            index=[0, 1, 3, 5, 6, 8, 9, 9, 9],
        )
ddf = dd.from_pandas(pdf, npartitions=3)

gb = ddf.groupby(ddf.b > 4).a

assert gb.count().index.dtype == bool  # good
assert gb.sum().index.dtype == bool  # good
assert gb.mean().index.dtype == object  # bad (implemented as sum() / count(), see link below)
## and also:
assert (gb.sum() / gb.count()).index.dtype == object  # bad

dask/dask/dataframe/groupby.py

Lines 1424 to 1429 in d670db6

def mean(self, split_every=None, split_out=1):
s = self.sum(split_every=split_every, split_out=split_out)
c = self.count(split_every=split_every, split_out=split_out)
if is_dataframe_like(s):
c = c[s.columns]
return s / c

Anything else we need to know?:

Environment:

  • Dask version: main (d670db6)
  • Pandas: upstream (1.5.0.dev0+350.g0631637205)
  • Python version: 3.9.10
  • Operating System: Mac OS 12.2.1 (21D62)
  • Install method (conda, pip, source): source
Cluster Dump State:

Activity

  1. jrbourbeau commented on Feb 15, 2022

    @jrbourbeau
    Member

    Thanks @phobson @ncclementi, I'm able to reproduce the dtype mismatch issue. Experimenting a bit locally, I was able to reproduce the same issue with a slightly simpler example that just divides two Dask Series (so avoiding groupby altogether):

    import pandas as pd
    import dask.dataframe as dd
    
    # Ratio of two pandas Series
    x = pd.Series([1, 2, 3], index=[True, False, False])
    y = pd.Series([4, 5, 6], index=[False, True, False])
    z = x / y
    
    # Dask version
    dx = dd.from_pandas(x, npartitions=2)
    dy = dd.from_pandas(y, npartitions=2)
    dz = dx / dy
    
    assert z.index.dtype is dz.index.compute().dtype
    assert z.index.dtype is dz.index.dtype, f"{repr(z.index.dtype)} is not {repr(dz.index.dtype)}"

    Interestingly, if we actually compute() the Dask Index, then we get the same dtype as what we would expect from pandas (i.e. assert z.index.dtype is dz.index.compute().dtype). This makes me think the issue is an issue with our DataFrame meta inference. The next place I'd look would be our Series truediv implementation (that should be the method that gets called when we use the / operator)

  2. added
    tests
    on Feb 15, 2022
  3. phobson commented on Feb 15, 2022

    @phobson
    ContributorAuthor

    Thanks for the direction, @jrbourbeau. I'll coordinate with Naty.

  4. jrbourbeau commented on Feb 16, 2022

    @jrbourbeau
    Member

    @ncclementi @phobson and I did some pairing on this issue and narrowed things down to this change being useful

    diff --git a/dask/dataframe/backends.py b/dask/dataframe/backends.py
    index e8ee26ed..57b898ca 100644
    --- a/dask/dataframe/backends.py
    +++ b/dask/dataframe/backends.py
    @@ -194,7 +194,7 @@ def _nonempty_index(idx):
         elif idx.is_numeric():
             return typ([1, 2], name=idx.name)
         elif typ is pd.Index:
    -        return pd.Index(["a", "b"], name=idx.name)
    +        return pd.Index(["a", "b"], name=idx.name, dtype=idx.dtype)
         elif typ is pd.DatetimeIndex:
             start = "1970-01-01"
             # Need a non-monotonic decreasing index to avoid issues with

    Just posting this here for completeness. This may break other tests, I'm not sure yet. @ncclementi would you mind pushing up a PR to see if the test suite is happy with this change?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

dataframetestsupstream

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions