Repository navigation
Closed
Labels
Description
I ran across an issue where set_index fails when the column that's being set to the index has a dtype of Int64 (an extension dtype from pandas). Here's a reproducer:
import numpy as np
import pandas as pd
import dask.dataframe as dd
df = pd.DataFrame({"a": [1, np.nan, 3], "b": [4, 5, 6]})
df = df.astype({"a": "Int64", "b": "int"})
ddf = dd.from_pandas(df, npartitions=2)
# Column "a" is Int64, while "b" is normal int64
print(f"ddf.dtypes = {ddf.dtypes}")
# set_index on int64 column works
print(f"ddf.set_index('b') = {ddf.set_index('b')}")
# set_index on Int64 column fails
print(f"ddf.set_index('a') = {ddf.set_index('a')}")fails with TypeError: data type not understood
Full traceback:
ddf.dtypes = a Int64
b int64
dtype: object
ddf.set_index('b') = Dask DataFrame Structure:
a
npartitions=1
4 Int64
6 ...
Dask Name: sort_index, 3 tasks
Traceback (most recent call last):
File "set_index_extension_type.py", line 14, in <module>
print(f"ddf.set_index('a') = {ddf.set_index('a')}")
File "/Users/jbourbeau/github/dask/dask/dask/dataframe/core.py", line 3532, in set_index
**kwargs
File "/Users/jbourbeau/github/dask/dask/dask/dataframe/shuffle.py", line 71, in set_index
divisions, sizes, mins, maxes, optimize_graph=False
File "/Users/jbourbeau/github/dask/dask/dask/base.py", line 436, in compute
results = schedule(dsk, keys, **kwargs)
File "/Users/jbourbeau/github/dask/dask/dask/threaded.py", line 81, in get
**kwargs
File "/Users/jbourbeau/github/dask/dask/dask/local.py", line 486, in get_async
raise_exception(exc, tb)
File "/Users/jbourbeau/github/dask/dask/dask/local.py", line 316, in reraise
raise exc
File "/Users/jbourbeau/github/dask/dask/dask/local.py", line 222, in execute_task
result = _execute_task(task, data)
File "/Users/jbourbeau/github/dask/dask/dask/core.py", line 119, in _execute_task
return func(*args2)
File "/Users/jbourbeau/github/dask/dask/dask/dataframe/partitionquantiles.py", line 415, in percentiles_summary
vals, n = _percentile(data, qs, interpolation=interpolation)
File "/Users/jbourbeau/github/dask/dask/dask/array/percentile.py", line 25, in _percentile
if np.issubdtype(a.dtype, np.datetime64):
File "/Users/jbourbeau/miniconda/envs/dask-dev/lib/python3.7/site-packages/numpy/core/numerictypes.py", line 393, in issubdtype
arg1 = dtype(arg1).type
TypeError: data type not understood
It looks like when we compute the divisions here
dask/dask/dataframe/shuffle.py
Line 65 in 95ab6ee
| divisions = index2._repartition_quantiles(npartitions, upsample=upsample) |
we pass the column dtype to NumPy here
Line 25 in 95ab6ee
| if np.issubdtype(a.dtype, np.datetime64): |
which is where the breakage occurs
Reacted by Ricardo Savii, Zhuyi Xue, Lolo Soto and Dave Hirschfeld
Activity
TomAugspurger commentedon Dec 17, 2019
FYI, pandas doesn't have a concept of an "ExtensionIndex", so the nullable integer type is converted to a NumPy-backed Index along the way.
jrbourbeau commentedon Dec 17, 2019
Ah thanks, that's very good to know! So we could check if the new index dtype is an extension dtype and if so convert it to dtype
object?TomAugspurger commentedon Dec 17, 2019
That's probably best, but we'll need to be careful since pandas has implemented indexes for specific types (datetime64[ns, tz], categorical, interval, period).
kevinpauli commentedon Oct 9, 2020
I am running into this, as you have warned @TomAugspurger, with a type of datetime64[ns, UTC]. I don't understand what I'm supposed to do to avoid it, however. Here is the error:
distributed.worker - WARNING - Compute Failed
Function: execute_task
args: ((subgraph_callable, (<function pandas_read_text at 0x7f9eb2b55b00>, <function _make_parser_function..parser_f at 0x7f9ea7406c20>, (<function read_block_from_file at 0x7f9eb3086320>, <OpenFile '/Users/kevinpauli/projects/my-proj/data/2.csv'>, 0, 64000000, b'\n'), b'col_1,col_2,change_timestamp,status\n', {'dtype': {'col_1': <class 'str'>, 'col_2': <class 'str'>, 'status': <class 'str'>}, 'parse_dates': ['change_timestamp']}, {col_1': dtype('O'), 'col_2': dtype('O'), 'change_timestamp': datetime64[ns, UTC], 'status': dtype('O')}, ['col_1', 'col_2', 'change_timestamp', 'status'], False, False, None), 'col_1'))
kwargs: {}
Exception: TypeError('data type not understood')
TomAugspurger commentedon Oct 9, 2020
@kevinpauli pandas has an index type for
datetime64[ns, tz]. Do you have a reproducible example giving that error?jsignell commentedon Mar 19, 2021
The error has changed now, but the reproducer still raises an error. I think that we need a different way of checking dtypes rather than relying on
np.issubdtype(data.dtype, np.integer). This is related to #7375.--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-11-d242bf2d475d> in <module> 12 print(f"ddf.set_index('b') = {ddf.set_index('b')}") 13 # set_index on Int64 column fails ---> 14 print(f"ddf.set_index('a') = {ddf.set_index('a')}") ~/dask/dask/dataframe/core.py in set_index(***failed resolving arguments***) 3914 from .shuffle import set_index 3915 -> 3916 return set_index( 3917 self, 3918 other, ~/dask/dask/dataframe/shuffle.py in set_index(df, index, npartitions, shuffle, compute, drop, upsample, divisions, partition_size, **kwargs) 490 mins = index2.map_partitions(M.min) 491 maxes = index2.map_partitions(M.max) --> 492 divisions, sizes, mins, maxes = base.compute(divisions, sizes, mins, maxes) 493 divisions = methods.tolist(divisions) 494 if type(sizes) is not list: ~/dask/dask/base.py in compute(*args, **kwargs) 563 postcomputes.append(x.__dask_postcompute__()) 564 --> 565 results = schedule(dsk, keys, **kwargs) 566 return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)]) 567 ~/dask/dask/threaded.py in get(dsk, result, cache, num_workers, pool, **kwargs) 74 pools[thread][num_workers] = pool 75 ---> 76 results = get_async( 77 pool.apply_async, 78 len(pool._pool), ~/dask/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs) 485 _execute_task(task, data) # Re-execute locally 486 else: --> 487 raise_exception(exc, tb) 488 res, worker_id = loads(res_info) 489 state["cache"][key] = res ~/dask/dask/local.py in reraise(exc, tb) 315 if exc.__traceback__ is not tb: 316 raise exc.with_traceback(tb) --> 317 raise exc 318 319 ~/dask/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception) 220 try: 221 task, data = loads(task_info) --> 222 result = _execute_task(task, data) 223 id = get_id() 224 result = dumps((result, id)) ~/dask/dask/core.py in _execute_task(arg, cache, dsk) 119 # temporaries by their reference count and can execute certain 120 # operations in-place. --> 121 return func(*(_execute_task(a, cache) for a in args)) 122 elif not ishashable(arg): 123 return arg ~/dask/dask/core.py in <genexpr>(.0) 119 # temporaries by their reference count and can execute certain 120 # operations in-place. --> 121 return func(*(_execute_task(a, cache) for a in args)) 122 elif not ishashable(arg): 123 return arg ~/dask/dask/core.py in _execute_task(arg, cache, dsk) 113 """ 114 if isinstance(arg, list): --> 115 return [_execute_task(a, cache) for a in arg] 116 elif istask(arg): 117 func, args = arg[0], arg[1:] ~/dask/dask/core.py in <listcomp>(.0) 113 """ 114 if isinstance(arg, list): --> 115 return [_execute_task(a, cache) for a in arg] 116 elif istask(arg): 117 func, args = arg[0], arg[1:] ~/dask/dask/core.py in _execute_task(arg, cache, dsk) 119 # temporaries by their reference count and can execute certain 120 # operations in-place. --> 121 return func(*(_execute_task(a, cache) for a in args)) 122 elif not ishashable(arg): 123 return arg ~/dask/dask/dataframe/partitionquantiles.py in percentiles_summary(df, num_old, num_new, upsample, state) 414 data = data.codes 415 interpolation = "nearest" --> 416 elif np.issubdtype(data.dtype, np.integer) and not is_cupy_type(data): 417 # CuPy doesn't currently support "nearest" interpolation, 418 # so it's special cased in the condition above. ~/conda/envs/dask-dev/lib/python3.8/site-packages/numpy/core/numerictypes.py in issubdtype(arg1, arg2) 417 """ 418 if not issubclass_(arg1, generic): --> 419 arg1 = dtype(arg1).type 420 if not issubclass_(arg2, generic): 421 arg2 = dtype(arg2).type TypeError: Cannot interpret 'Int64Dtype()' as a data typeTomAugspurger commentedon Mar 19, 2021
Just an FYI, I think pandas considers
DataFrame.set_index("nullable_dtype_column")converting from a nullable Int64Dtype to a NumPy dtype to be a bug, and so it might be fixed in any version (there's some effort underway now). We could match pandas bug-for-bug here, but maybe it's best to have users do the conversion if that's really what they want. Then when pandas adds support for extension indexes we can implement support for it in dask.jorloplaz commentedon Feb 21, 2022
Following on @TomAugspurger 's comment and a conversation on Slack with @jsignell, Pandas now supports indexation by an ExtensionDtype from its 1.4 release.
So, if Dask fails, it should be because it relies at some point on some specific
numpy-related code and doesn't delegate on Pandas for that. I don't know if it's just theissubdtypefrom this simple example that ruins everything, but note how in Pandas it's perfectly possible (compute().set_index('c')), while in Dask it doesn't work (set_index('c').compute()):TomAugspurger commentedon Feb 21, 2022
Yeah, we will need find all the calls to NumPy functions in partionquantiles and make sure that we’re just using functions from the extension array interface.
jorloplaz commentedon Mar 2, 2022
Actually, there seems to be an incompatibility in the very deep
meta_from_array. This makes.valuesfail miserably, even when.compute()is not called. Perhaps it should bedtype.kindand notdtypeitself that should be passed? @TomAugspurger :TomAugspurger commentedon Mar 2, 2022
I'm not sure off hand. It might be worth seeing what we do with Categorical / CategoricalIndex.