Skip to content

DataFrame: handle ExtensionArrays when converting to dask.Array - #7375

Open
gjoseph92 wants to merge 17 commits into
dask:mainfrom
gjoseph92:ddf-to-da-handle-extension-arrays
Open

gjoseph92 wants to merge 17 commits into
dask:mainfrom
gjoseph92:ddf-to-da-handle-extension-arrays

Conversation

@gjoseph92

@gjoseph92 gjoseph92 commented Mar 12, 2021 •

Copy link
Copy Markdown
Collaborator

In #7206, computing the meta from a column containing a pandas ExtensionArray failed, because we were assuming the chunk type of the resulting array would always be a NumPy array, which doesn't know what to make of a pandas extension dtype.

There are two approaches we could take:

  1. (56757b3 only) use to_numpy() instead of .values (as recommended), to be sure that any extension arrays are converted to NumPy arrays (both in the meta, and the actual compute).
  2. (+ c15c4ea) Keep using .values, and let a pandas ExtensionArray be the meta of a Dask array. This avoids an (in some cases expensive) conversion, but might lead to weird downstream behavior, since the extension arrays aren't registered as dask chunk types, plus they can only be 1D.

Update: went with approach 1 (coerce to a NumPy array) after discussing with @jrbourbeau: we were unsure whether ExtensionArrays would behave correctly as chunk types and the API is still moving around, so let's play it safe and stick with NumPy for now.

In either case, I also extended to_dask_array to match to_numpy, so you can specify a dtype and na_value, which will be handy as the extension array types become more prevalent.

@TomAugspurger any thoughts on which approach to take?

Computing the `meta` from a pandas ExtensionArray column failed, because though ExtensionArrays _are_ "array-like", NumPy doesn't support their dtypes.

More broadly, as ExtensionArrays become more widely used in pandas, we should also prefer `to_numpy()` over `.values` [as recommended](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.values.html#pandas.DataFrame.values), at least until the various ExtensionArray types are registered as duck arrays.

I also extended `to_dask_array` to match [`to_numpy`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy), so you can specify a dtype and na_value.
@gjoseph92
gjoseph92 force-pushed the ddf-to-da-handle-extension-arrays branch from 2964e54 to a59634b Compare March 12, 2021 04:43
Comment thread dask/dataframe/tests/test_dataframe.py Resolved
Comment thread dask/dataframe/utils.py Resolved
Comment thread dask/dataframe/core.py Resolved

@TomAugspurger TomAugspurger left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for looking into this. Seems good based on a quick skim.

If you're interested in this general area, #5001 might be fun to think about in the background.

Comment thread dask/dataframe/core.py Resolved
Comment thread dask/dataframe/methods.py Resolved
Comment thread dask/dataframe/tests/test_dataframe.py Resolved
Comment thread dask/dataframe/utils.py Resolved

@jrbourbeau jrbourbeau left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this @gjoseph92! Just as a heads up we use flake8 and black for code formatting (xref https://docs.dask.org/en/latest/develop.html#code-formatting). I recommend installing our pre-commit hooks too (though they're not required)

Comment thread dask/dataframe/core.py
lengths = tuple(self.map_partitions(len, enforce_metadata=False).compute())

arr = self.values
arr = self.map_partitions(methods.to_numpy, _dtype=dtype, na_value=na_value)

@jrbourbeau jrbourbeau Mar 12, 2021 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @quasiben will this cause problems with a cuDF-backed Dask DataFrame? I'm actually not sure what happens today with to_dask_array in that case

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes this will. I'm not sure what we should do on the cuDF front here because we could either have to_numpy return a CuPy array, or have it do an explicit device to host copy, neither of which is clear and good behavior.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Today, .values will return a CuPy array which can live behind a dask array happily.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is absolutely necessary, we could have method.to_numpy currently return df.values if "cudf" in str(type(df)), for example, but of course this will look a strange.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the input @kkraus14 @pentschev. We were worried about that.

I opened #7399 to implement "approach 2" as given in this PR's description. That change would allow us to use .values here instead of to_numpy, which is sounding like the better option to me.

@jrbourbeau we were worried that pandas ExtensionArrays might not currently behave well as dask Array chunks (particularly since they're 1D only), hence the to_numpy cast. Since it's seeming like .values is the more correct approach overall, should I spend a little time seeing how ExtensionArrays actually behave as chunks, or should we go with @pentschev's "cudf" in str(type(df)) trick for now, merge this, and revisit it later?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gjoseph92, @jsignell, @jrbourbeau, and I met today. We discussed this. A few other ideas we came up with are

  • Using .array ( Add Series.array #5001 ). Though this is Series only AFAICT and I don't think we implement this in cuDF to (feel free to correct me though)
  • Calling .fillna beforehand and continuing to use .values. Possibly concerns about performance. Though this should work with Pandas and cuDF today. Though I think this doesn't work quite correctly for some Pandas ExtensionArrays (feel free to correct me if I got that wrong Gabe)

Feel free to add anything else or correct anything I got wrong above

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should add I think a 3rd option (in addition to the other ideas above and ones discussed) might be Dask provides a dispatch function that Pandas and cuDF implementations can be registered with

Comment thread dask/array/utils.py Resolved

@jrbourbeau jrbourbeau left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @gjoseph92!

Comment thread dask/dataframe/core.py Resolved
Comment thread dask/dataframe/methods.py

def values(df):
return df.values
def to_numpy(df, _dtype, na_value):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: Do we need the leading underscore for dtype?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't. Nothing in map_partitions, _emulate, or new_dd_object actually uses a kwarg namd dtype. It just seemed like an argument name that was at a high risk of being consumed by some (future) logic in map_partitions, so I added the underscore as an overly-conservative guard against that. Happy to remove it if you don't think that's worth worrying about.

Comment thread dask/dataframe/methods.py
try:
if na_value == no_default: # `==` not `is`, since it could be pickled
na_value = pd_no_default
except Exception:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a more specific exception we can catch here? When I do bool(pd.NA == dd.core.no_default) I get TypeError: boolean value of NA is ambiguous

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, we could catch TypeError here instead. I was trying to be general to any possible user-defined ExtensionArray type, where maybe? you could have your own custom NA type, which raised a different sort of error in __bool__. Happy to switch to TypeError and not worry about that for now if you'd prefer, or add a comment explaining this.

Comment thread dask/dataframe/methods.py
# could be pd.NA, where __bool__ will raise an error
pass
kwargs["na_value"] = na_value
return df.to_numpy(**kwargs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: Could we pass explicit keyword arguments here? I think it will be easier for future maintainers to reason about if they know immediately what the possible keywords are

@gjoseph92 gjoseph92 Mar 15, 2021 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could, but since pandas < 1.1.0 doesn't support the na_value kwarg in to_numpy, we'd have to do it like:

if PANDAS_GT_110:
    return df.to_numpy(dtype=_dtype, na_value=na_value)
else:
    return df.to_numpy(dtype=_dtype)

Would you prefer that?

Comment thread dask/dataframe/tests/test_dataframe.py Resolved
Comment thread dask/dataframe/tests/test_dataframe.py Resolved
Comment thread dask/dataframe/tests/test_dataframe.py Resolved
Comment thread dask/dataframe/core.py Resolved
Comment thread dask/dataframe/tests/test_dataframe.py Resolved
Comment thread dask/dataframe/methods.py

def values(df):
return df.values
def to_numpy(df, _dtype, na_value):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this is just following the Pandas API, but this is problematic for cuDF and possibly any other future library that could live underneath Dask DataFrame.

@github-actions github-actions Bot added the needs attention It's been a while since this was pushed on. Needs attention from the owner or a maintainer. label Nov 4, 2024

This branch has not been deployed

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

Labels

needs attention It's been a while since this was pushed on. Needs attention from the owner or a maintainer.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug with delayed head-method for pandas string columns

6 participants