Skip to content

DataFrame metadata cleanup - #1422

Merged
jcrist merged 19 commits into
dask:masterfrom
jcrist:df-dtype-cleanup
Aug 9, 2016
Merged

jcrist merged 19 commits into
dask:masterfrom
jcrist:df-dtype-cleanup

Conversation

@jcrist

@jcrist jcrist commented Jul 28, 2016 •

Copy link
Copy Markdown
Member

This PR is an attempt to enforce that dask dataframes always know their full metadata (fixes #1209). Previously we allowed partial knowledge, with full dtype/column name computation done lazily if needed. This seemed like a good idea at the time, but masked many hidden metadata inference issues (functions could forget to pass along dtype, and we'd just recompute later). We also had to keep track of which bits of metadata were known, and which were unknown, resulting in frequent incorrect dtype inference.

Inference with pandas is much trickier than it is with numpy, as the dtype of the output series can change depending on values as well as input dtypes. Some functions also return different dtypes if a series is empty vs if it isn't. To get around this, a _pd_nonempty attribute is added to all _Frame objects, which matches _pd's metadata, but contains one row of fake data. This helps for many situations, but not all.

Todo:

  • Figure out a way to smoothly deprecate the old behavior (unless we decide to make this a breaking change)
  • Figure out a good way to handle methods that take user provided functions like apply, map_partitions, etc...
  • Improve test suite to check that metadata actually matches on outputs.

jcrist added 6 commits July 28, 2016 16:23
- Forbid untyped dataframes, removing optional `dtype` compute. This
  causes lots of errors that need to be squashed
- Start adding metadata inference in places where it's missing.
- Rename `nonempty_sample_df` to `nonempty_pd`. Make work with
  `pd.Series`, `pd.DataFrame` and `pd.Index` objects. Ensure that names,
  dtype, index type, and index name are all appropriately copied.
- Move `_pd_nonempty` property to `_Frame` base class
- Improve metadata inference for reductions.
No longer needed?
@nirizr

nirizr commented Jul 28, 2016 •

Copy link
Copy Markdown
Contributor

Follow + volunteer to contribute.

Right now I am manually creating dask dataframes and enjoy dask's ability to keep going without full knowledge prior to computation.
Therefore this interests me both as a "test subject" and as a way to make internal adjustments before the change is released.

Actually, to be honest - this scares me a little. I'll manage though, and i'm probably not the common case here.

Comment thread dask/dataframe/categorical.py Outdated
return df.map_partitions(func, columns=df.columns)

meta = func(df._pd)
return df.map_partitions(func, columns=meta)

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.

Request that we eventually change columns= to meta= or some other word like empty, sample, dummy, etc..

@mrocklin

Copy link
Copy Markdown
Member

Figure out a good way to handle methods that take user provided functions like apply, map_partitions, etc...

Try the function on _nonempty_pd and if it works great, if it doesn't try on _pd and if that doesn't work then raise an error?

@mrocklin

Copy link
Copy Markdown
Member

Improve test suite to check that metadata actually matches on outputs.

Hooray eq!

@jcrist

jcrist commented Aug 4, 2016 •

Copy link
Copy Markdown
Member Author

This is proving more difficult than expected. The main source of frustration is the implicit conversion of integers to floats if an operation finds missing data. For example, joining two indexed dataframes together with integer columns may result in integer columns or float columns, depending on if any missing rows are found in the join. This is impossible to infer beforehand, and is also impossible to infer by just evaluating the first few rows of a partition (as is currently done) because it depends on a global presence of missingness in the column.

I'm not sure what to do here. Perhaps just do our best, but don't necessarily error in tests if numeric dtypes differ for operations where missingness can appear?

@mrocklin

mrocklin commented Aug 4, 2016

Copy link
Copy Markdown
Member

That sounds reasonable to me. The only checks that really seem to care about this seem to be checks for number-y-ness. Alternatively we could coerce everything to float if it came to that?

jcrist added 9 commits August 5, 2016 12:37
- `eq` now checks that the inferred dtypes match the computed dtypes.
  Note that all numeric types are compared equally, as pandas will
  implicitly convert integers to floats in the presence of missing data,
  which makes inference *hard*. There's not an obvious good way around
  this, so this will do for now.

- `nonempty_pd` now returns 2 rows. Due to some bugs in pandas, there
  are differences in behavior between 1 row and 2 rows for some
  operations.
Notably `from_dask_array` inference with struct dtype now matches.
Cleaned up a few implementation details of that inference function.
The implementation of `from_castra` lives in the castra repo, and
doesn't propogate the dtype information, resulting in test failures.
Xfailing these for now.
If not provided, metadata inference is first tried on fake data. If that
fails, it's then tried on `head()`. If that fails, then we error, and
suggest the user provide `meta`.
Add in `meta` keyword to dask.dataframe use functions (`map_partitions`,
`apply`, `map`, etc...). A few other small things to squash throughout,
and everything *should* pass fine now.
No longer needed, covered by the `make_meta` function.
More consistent naming of arguments/variables.
More robust to older versions of pandas.
@jcrist

jcrist commented Aug 5, 2016 •

Copy link
Copy Markdown
Member Author

This is ready for review. A few notes:

  • In some places there are breaking changes to the api. These are limited to only non-pandas replicating functions (e.g. map_partitions, elemwise, apply_concat_apply), as I feel users making use of these will be more willing to update their code (also, probably have fewer users here).

  • All constructors now will error if metadata isn't provided on construction. For most users this won't be a problem, but it's also currently a breaking change. I'm apt to punt on this and not deprecate smoothly, but I could be persuaded to deprecate nicely if needed.

  • All places that take metadata can take either:

    • A pandas object
    • A dict of {name: dtype} (from which a dataframe will be constructed)
    • A tuple of (name, dtype) (from which a series will be constructed)

    This was the best "easy" api I could come up with, and I'm pretty happy with it. If you have a better idea, I'd love to hear it.

  • I know I still need to up coverage in a few places. Waiting for feedback/not a friday evening :/.

@jcrist jcrist changed the title [WIP] DataFrame metadata cleanup DataFrame metadata cleanup Aug 5, 2016
@mrocklin

mrocklin commented Aug 5, 2016

Copy link
Copy Markdown
Member

In the dict case how do we determine the order of the columns?

@jcrist

jcrist commented Aug 5, 2016

Copy link
Copy Markdown
Member Author

That's a good point, I suppose we don't. This hasn't come up yet, as all cases where I've used the dict case, I've also created the dataframe with a dict, so pandas default ordering worked. Perhaps a list of tuples instead of a dict?


msg = r"from_array does not input more than 2D array, got array with shape \(3, 3, 3\)"
with tm.assertRaisesRegexp(ValueError, msg):
with pytest.raises(ValueError):

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.

Why this change?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I had to change how that function was implemented, and pulled the error checking into our code (which changed what they read). I didn't see the value in checking that the messages matched, but could change back if desired.

@mrocklin

mrocklin commented Aug 5, 2016

Copy link
Copy Markdown
Member

At a first glance through this all looks pretty reasonable to me. I haven't checked things like coverage though.

jcrist added 3 commits August 8, 2016 11:45
More consistent naming througout.
- Remove inference from `df.head()`, as it can be slow and unexpected.
  Seems more sane to error in these cases and inform the user.
- Change error message in `make_meta`.
- A few small doc/pep8 fixes.
@jcrist

jcrist commented Aug 8, 2016 •

Copy link
Copy Markdown
Member Author

Ok, I think this is good to go now (minus a good review). I expect there might be some unexpected fallout from this, so it'd be good to get it in master soon so others can start playing with it and finding the edge cases that I couldn't. A few breaking changes I'd like to point out:

  • df.map_partitions signature is changed without a deprecation (there wasn't an easy way to change it in a backwards compatible way).

    # old signature
    df.map_partitions(self, func, columns=no_default, *args, **kwargs)
    # new signature
    df.map_partitions(self, func, *args, **kwargs)    # meta is in `kwargs`

    The reason for this change was that the old signature made it impossible to pass in args without providing something to columns. Coupled with the desire to rename the columns keyword, and the fact that many internal uses of map_partitions passed in columns as a positional, it was difficult to find a way to smoothly deprecate. It should be noted that the function dd.map_partitions only has a positional renamed, and remains the same otherwise. I could be convinced to revert this change if needed.

  • All object constructors (i.e. dd.DataFrame) will now error if not fully typed. This shouldn't affect most users, but is a breaking change for those mucking around in dataframe internals. I could probably find a way to smoothly deprecate that, but I'd rather not.

  • _pd and _pd_nonempty have been renamed to _meta and _meta_nonempty. No deprecation of the old attributes, as they were internal api. Could deprecate easily if desired.

  • Several positional arguments have been renamed, mostly in the internal api. This should only affect users that were using those internals, and passing in positionals as keywords. I doubt this is common, but it is a breaking change.

Everything else should be a smooth transition. Functions like map and apply have the columns keyword deprecated in favor of meta.

Comment thread dask/dataframe/core.py Outdated
Arguments and keywords to pass to the function. The partition will
be the first argument, and these will be passed *after*.
meta : pd.DataFrame, pd.Series, dict, tuple, optional
Metadata describing the output DataFrame or Series. Should have

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.

Suggest something like the following:

An empty pandas DataFrame or Series that matches the dtypes and column names of the output. Alternatively ...

Leading with the term metadata might be confusing to newcomers.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed.

@mrocklin

mrocklin commented Aug 8, 2016

Copy link
Copy Markdown
Member

_pd was sufficiently widespread that I think it would be good to deprecate it with a property, even though it was internal.

- `apply_concat_apply` now infers metadata if not provided
- docstring description for `meta` parameter is shared between all
  functions that need it, through the use of a decorator
- `map_partitions` function matches `map_partitions` method
- Re-add `_pd` and `_pd_nonempty` attributes as deprecated properties
- Deprecate `metadata` keyword to `dd.from_delayed`, replace with
  `meta`. Improve docstring for `meta` here.
- a few docstring cleanups
@jcrist

jcrist commented Aug 9, 2016

Copy link
Copy Markdown
Member Author

Anything else here? Planning to merge later today if no comment.

@mrocklin

mrocklin commented Aug 9, 2016

Copy link
Copy Markdown
Member

Nothing from me. +1 to merge

@jcrist
jcrist merged commit 8d3db66 into dask:master Aug 9, 2016
@jcrist
jcrist deleted the df-dtype-cleanup branch August 9, 2016 15:55
jcrist added a commit to jcrist/castra that referenced this pull request Aug 9, 2016
After dask dask/dask#1422, dask dataframe
mandates that all dask dataframes are fully typed. Previously
`to_dask` wouldn't result in a fully typed dataframe, this fixes that.
jcrist added a commit to jcrist/dask that referenced this pull request Aug 9, 2016
These were xfailed in dask#1422, as the
last release of castra was incompatible with the new metadata. This was
fixed in blaze/castra#64, and a new release was
made (0.1.8). We now only run these tests if castra version is >= 0.1.8
@jcrist jcrist mentioned this pull request Aug 9, 2016
jcrist added a commit that referenced this pull request Aug 10, 2016
These were xfailed in #1422, as the
last release of castra was incompatible with the new metadata. This was
fixed in blaze/castra#64, and a new release was
made (0.1.8). We now only run these tests if castra version is >= 0.1.8
@sinhrks sinhrks added this to the 0.11.0 milestone Aug 22, 2016
@jcrist jcrist mentioned this pull request Nov 3, 2016
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Dask.dataframe metadata handling loses information

4 participants