Repository navigation
Closed
Labels
dataframeneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.
Description
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 5xref #5720?
Environment:
- Dask version: c2278fe
- Python version: 3.8.8
- Operating System: macOS
- Install method (conda, pip, source): source
Metadata
Metadata
Assignees
Labels
dataframeneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.
Activity
jsignell commentedon Nov 5, 2021
Yeah I think raising a better error is probably good enough.
jorloplaz commentedon Apr 13, 2022
I'm currently dealing with this, raising an error if any
NaNis found.This is definitely what should be done in Dask, because
divisionsrely on being comparable and distinct from each other (except possiblydivisions[-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 shouldpdf.index.is_monotonic_increasingyield on the example written by @gjoseph92 in view of the following?False,NA, and error raised or what?Hope to have a PR by next week!
jsignell commentedon Apr 18, 2022
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_increasingshould beFalsejorloplaz commentedon Apr 19, 2022
Yes, but in this case for Dask it's very important that the
indexis sorted (wheneverknown_divisionsisTrue). That's why you have thesortedflag inset_index, all thepartitionquantilescode, etc. And as a result the elements indivisionsmust 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
divisionsand unicity, we can come back to this. So perhaps aNotImplementedErrorwould be the best here?jsignell commentedon Apr 19, 2022
Yeah that makes sense. A
NotImplementedErroruntil we can come up with a more robust plan seems like a good choice.jorloplaz commentedon Apr 21, 2022
Just made a PR with this. I think the result is rather neat, hope you find it so!
jorloplaz commentedon May 6, 2022
In the end, my PR only complains and informs the user about nulls when 2 things happen:
nan, but alsoNone,pd.NaT, etc.)dtype.When it is numeric things apparently work fine. Nevertheless, I'm not sure at all it makes sense to allow for that, since:
na_positionargument for specifying this.None != pd.NA), so I think this isn't guaranteed either for a generalobjectcolumn which could hold anything that is considered null viapd.isna().So then what?
jsignell commentedon May 10, 2022
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_positionargument 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?jorloplaz commentedon May 10, 2022
I agree
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
nanvalues"), but also about having those values sorted. And here is when problems arise: isNone >= nan, or is itnan <= None, once we agreed on the fact thatnan != None? Arebisectmethods robust to nulls? Doesn't look that way, because you're preventing explicitly that there's anynanindivisions.Moreover,
Noneis used to indicate unknown divisions, and once there's aNonein somedivision, all otherdivisionsmust beNoneas well. But what if there's actually a partition that's only meant to store the valueNoneitself? ThatNoneshould 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.