Skip to content

set_index on a column containing NaN raises confusing error (partition_quantiles not robust to NaNs) #8347

Closed

Description

@gjoseph92

Minimal Complete Verifiable Example:

import pandas as pd
import dask.dataframe as dd

pdf = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": ["a", "b", float('nan'), "a", float('nan')]})
df = dd.from_pandas(pdf)
df.set_index("B")
# TypeError: '>=' not supported between instances of 'str' and 'float'
Full traceback
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-d04e3b506594> in <module>
----> 1 df.set_index("B")

~/dev/dask/dask/dataframe/core.py in set_index(***failed resolving arguments***)
   4342             from .shuffle import set_index
   4343 
-> 4344             return set_index(
   4345                 self,
   4346                 other,

~/dev/dask/dask/dataframe/shuffle.py in set_index(df, index, npartitions, shuffle, compute, drop, upsample, divisions, partition_size, **kwargs)
    189 
    190     if divisions is None:
--> 191         divisions, mins, maxes = _calculate_divisions(
    192             df, index2, repartition, npartitions, upsample, partition_size
    193         )

~/dev/dask/dask/dataframe/shuffle.py in _calculate_divisions(df, partition_col, repartition, npartitions, upsample, partition_size)
     38     mins = partition_col.map_partitions(M.min)
     39     maxes = partition_col.map_partitions(M.max)
---> 40     divisions, sizes, mins, maxes = base.compute(divisions, sizes, mins, maxes)
     41     divisions = methods.tolist(divisions)
     42     if type(sizes) is not list:

~/dev/dask/dask/base.py in compute(*args, **kwargs)
    568         postcomputes.append(x.__dask_postcompute__())
    569 
--> 570     results = schedule(dsk, keys, **kwargs)
    571     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    572 

~/dev/dask/dask/threaded.py in get(dsk, result, cache, num_workers, pool, **kwargs)
     77             pool = MultiprocessingPoolExecutor(pool)
     78 
---> 79     results = get_async(
     80         pool.submit,
     81         pool._max_workers,

~/dev/dask/dask/local.py in get_async(submit, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, chunksize, **kwargs)
    505                             _execute_task(task, data)  # Re-execute locally
    506                         else:
--> 507                             raise_exception(exc, tb)
    508                     res, worker_id = loads(res_info)
    509                     state["cache"][key] = res

~/dev/dask/dask/local.py in reraise(exc, tb)
    313     if exc.__traceback__ is not tb:
    314         raise exc.with_traceback(tb)
--> 315     raise exc
    316 
    317 

~/dev/dask/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)
    218     try:
    219         task, data = loads(task_info)
--> 220         result = _execute_task(task, data)
    221         id = get_id()
    222         result = dumps((result, id))

~/dev/dask/dask/core.py in _execute_task(arg, cache, dsk)
    117         # temporaries by their reference count and can execute certain
    118         # operations in-place.
--> 119         return func(*(_execute_task(a, cache) for a in args))
    120     elif not ishashable(arg):
    121         return arg

~/dev/dask/dask/optimization.py in __call__(self, *args)
    967         if not len(args) == len(self.inkeys):
    968             raise ValueError("Expected %d args, got %d" % (len(self.inkeys), len(args)))
--> 969         return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
    970 
    971     def __reduce__(self):

~/dev/dask/dask/core.py in get(dsk, out, cache)
    147     for key in toposort(dsk):
    148         task = dsk[key]
--> 149         result = _execute_task(task, cache)
    150         cache[key] = result
    151     result = _execute_task(out, cache)

~/dev/dask/dask/core.py in _execute_task(arg, cache, dsk)
    117         # temporaries by their reference count and can execute certain
    118         # operations in-place.
--> 119         return func(*(_execute_task(a, cache) for a in args))
    120     elif not ishashable(arg):
    121         return arg

~/dev/dask/dask/utils.py in apply(func, args, kwargs)
     35 def apply(func, args, kwargs=None):
     36     if kwargs:
---> 37         return func(*args, **kwargs)
     38     else:
     39         return func(*args)

~/dev/dask/dask/dataframe/core.py in apply_and_enforce(*args, **kwargs)
   5948     func = kwargs.pop("_func")
   5949     meta = kwargs.pop("_meta")
-> 5950     df = func(*args, **kwargs)
   5951     if is_dataframe_like(df) or is_series_like(df) or is_index_like(df):
   5952         if not len(df):

~/dev/dask/dask/utils.py in __call__(self, _methodcaller__obj, *args, **kwargs)
   1019 
   1020     def __call__(self, __obj, *args, **kwargs):
-> 1021         return getattr(__obj, self.method)(*args, **kwargs)
   1022 
   1023     def __reduce__(self):

~/miniconda3/envs/dask-dev/lib/python3.8/site-packages/pandas/core/generic.py in stat_func(self, axis, skipna, level, numeric_only, **kwargs)
  11472         if level is not None:
  11473             return self._agg_by_level(name, axis=axis, level=level, skipna=skipna)
> 11474         return self._reduce(
  11475             func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only
  11476         )

~/miniconda3/envs/dask-dev/lib/python3.8/site-packages/pandas/core/series.py in _reduce(self, op, name, axis, skipna, numeric_only, filter_type, **kwds)
   4247                 )
   4248             with np.errstate(all="ignore"):
-> 4249                 return op(delegate, skipna=skipna, **kwds)
   4250 
   4251     def _reindex_indexer(self, new_index, indexer, copy):

~/miniconda3/envs/dask-dev/lib/python3.8/site-packages/pandas/core/nanops.py in f(values, axis, skipna, **kwds)
    127                     result = alt(values, axis=axis, skipna=skipna, **kwds)
    128             else:
--> 129                 result = alt(values, axis=axis, skipna=skipna, **kwds)
    130 
    131             return result

~/miniconda3/envs/dask-dev/lib/python3.8/site-packages/pandas/core/nanops.py in reduction(values, axis, skipna, mask)
    871                 result = np.nan
    872         else:
--> 873             result = getattr(values, meth)(axis)
    874 
    875         result = _wrap_results(result, dtype, fill_value)

~/miniconda3/envs/dask-dev/lib/python3.8/site-packages/numpy/core/_methods.py in _amax(a, axis, out, keepdims, initial, where)
     28 def _amax(a, axis=None, out=None, keepdims=False,
     29           initial=_NoValue, where=True):
---> 30     return umr_maximum(a, axis, None, out, keepdims, initial, where)
     31 
     32 def _amin(a, axis=None, out=None, keepdims=False,

TypeError: '>=' not supported between instances of 'str' and 'float'

Note that the error occurs eagerly while trying to calculate good divisions.

Setting a column containing NaNs as the index is probably a bad idea, so if we still want this to error, that would be reasonable. But an error like "Cannot calculate division for column "B" since it contains NaN values. Consider `.dropna(subset=["B"])` first." would be much more helpful.

Though it is a valid thing to do in Pandas:

>>> pdf.set_index("B")
     A
B     
a    1
b    2
NaN  3
a    4
NaN  5

xref #5720?

Environment:

  • Dask version: c2278fe
  • Python version: 3.8.8
  • Operating System: macOS
  • Install method (conda, pip, source): source

Activity

  1. jsignell commented on Nov 5, 2021

    @jsignell
    Member

    Yeah I think raising a better error is probably good enough.

  2. added
    needs attention
    on Dec 6, 2021
  3. jorloplaz commented on Apr 13, 2022

    @jorloplaz
    Contributor

    I'm currently dealing with this, raising an error if any NaN is found.

    This is definitely what should be done in Dask, because divisions rely on being comparable and distinct from each other (except possibly divisions[-1], see the discussion in #8845).

    I'm not sure actually that Pandas should tolerate such a thing; whenever there are NaNs, comparisons and equality are terribly confusing. For example, what should pdf.index.is_monotonic_increasing yield on the example written by @gjoseph92 in view of the following? False, NA, and error raised or what?

    # Numpy's nan
    >>> from numpy import nan
    >>> nan == nan
    False
    >>> nan != nan
    True
    >>> nan is nan
    True
    >>> float('nan') is float('nan')     # note the difference with `nan`
    False
    >>> nan == float('nan')
    False
    >>> nan > nan
    False
    >>> nan >= nan
    False
    >>> nan < nan
    False
    >>> nan <= nan
    False
    
    # Pandas NA for extension types
    from pandas import NA
    >>> NA == NA
    <NA>
    >>> NA != NA
    <NA>
    >>> NA > NA
    <NA>
    >>> NA >= NA
    <NA>
    >>> NA < NA
    <NA>
    >>> NA <= NA
    <NA>
    >>> NA is NA
    True
    >>> NA == nan
    <NA>

    Hope to have a PR by next week!

  4. jsignell commented on Apr 18, 2022

    @jsignell
    Member

    Thanks for engaging with this @jorloplaz! I agree that nans are often confusing, but luckily for dask the correct answer is always "whatever pandas does". So for instance is_monotonic_increasing should be False

  5. jorloplaz commented on Apr 19, 2022

    @jorloplaz
    Contributor

    Yes, but in this case for Dask it's very important that the index is sorted (whenever known_divisions is True). That's why you have the sorted flag in set_index, all the partitionquantiles code, etc. And as a result the elements in divisions must be unique and, more importantly, comparable among each other.

    That's why I strongly advocate for raising an error if trying to set an index with some missing value in that column. Maybe in the future when we settle things regarding divisions and unicity, we can come back to this. So perhaps a NotImplementedError would be the best here?

  6. jsignell commented on Apr 19, 2022

    @jsignell
    Member

    Yeah that makes sense. A NotImplementedError until we can come up with a more robust plan seems like a good choice.

  7. jorloplaz commented on Apr 21, 2022

    @jorloplaz
    Contributor

    Just made a PR with this. I think the result is rather neat, hope you find it so!

  8. jorloplaz commented on May 6, 2022

    @jorloplaz
    Contributor

    In the end, my PR only complains and informs the user about nulls when 2 things happen:

    1. There are nulls (not necessarily nan, but also None, pd.NaT, etc.)
    2. The series to become the index has a non-numeric dtype.

    When it is numeric things apparently work fine. Nevertheless, I'm not sure at all it makes sense to allow for that, since:

    • The index should be sorted, but it's ambiguous whether nulls should go first or last: see for example pd.sort_values(), which has an na_position argument for specifying this.
    • After this ambiguity is solved, all nulls should belong to the same partition, if comparisons proved equal... but different null values are different from each other! (e.g., None != pd.NA), so I think this isn't guaranteed either for a general object column which could hold anything that is considered null via pd.isna().

    So then what?

  9. jsignell commented on May 10, 2022

    @jsignell
    Member

    I think it's ok for this work to just improve the error messages on things that already fail.

    I would also be happy for dask to add a na_position argument like you suggest. As to your second point, this seems like an edge case, so would it really be so bad to have separate partitions for each null dtype?

  10. jorloplaz commented on May 10, 2022

    @jorloplaz
    Contributor

    I think it's ok for this work to just improve the error messages on things that already fail.

    I agree

    I would also be happy for dask to add a na_position argument like you suggest. As to your second point, this seems like an edge case, so would it really be so bad to have separate partitions for each null dtype?

    It could be a bit bad from the imbalancing perspective, because most values of a meaningful column shouldn't be null, so the "null-partition" should be already small enough for it to be partitioned in even smaller pieces to account for all possible different nulls.

    Anyhow, the biggest problem I see is that Dask's indexes aren't only about locating a particular value (e.g., "find me all nan values"), but also about having those values sorted. And here is when problems arise: is None >= nan, or is it nan <= None, once we agreed on the fact that nan != None? Are bisect methods robust to nulls? Doesn't look that way, because you're preventing explicitly that there's any nan in divisions.

    Moreover, None is used to indicate unknown divisions, and once there's a None in some division, all other divisions must be None as well. But what if there's actually a partition that's only meant to store the value None itself? That None should indicate a known division... And I think currently this isn't allowed.

    Pretty confusing, so we should agree on what should Dask do with nulls in an index, and be consistent with that decision.

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

    dataframeneeds attention

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions