Skip to content

DataFrame.set_index fails when column has pandas extension dtype #5720

Closed

Description

@jrbourbeau

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

divisions = index2._repartition_quantiles(npartitions, upsample=upsample)

we pass the column dtype to NumPy here

if np.issubdtype(a.dtype, np.datetime64):

which is where the breakage occurs

Activity

  1. TomAugspurger commented on Dec 17, 2019

    @TomAugspurger
    Member

    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.

  2. jrbourbeau commented on Dec 17, 2019

    @jrbourbeau
    MemberAuthor

    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?

  3. TomAugspurger commented on Dec 17, 2019

    @TomAugspurger
    Member

    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).

  4. kevinpauli commented on Oct 9, 2020

    @kevinpauli

    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')

  5. TomAugspurger commented on Oct 9, 2020

    @TomAugspurger
    Member

    @kevinpauli pandas has an index type for datetime64[ns, tz]. Do you have a reproducible example giving that error?

  6. jsignell commented on Mar 19, 2021

    @jsignell
    Member

    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 type
  7. TomAugspurger commented on Mar 19, 2021

    @TomAugspurger
    Member

    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.

  8. jorloplaz commented on Feb 21, 2022

    @jorloplaz
    Contributor

    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 the issubdtype from 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()):

    >>> ddf
    Dask DataFrame Structure:
                        a      b
    npartitions=1               
    0              object  int64
    1                 ...    ...
    Dask Name: assign, 9 tasks
    
    >>> ddf['c'] = ddf['b'].astype(pd.Int64Dtype())
    
    >>> ddf.dtypes
    a    object
    b     int64
    c     Int64
    dtype: object
    
    >>> ddf.set_index('b').compute()
         a  c
    b        
    1  NaN  1
    2  NaN  2
    
    >>> ddf.set_index('c').compute()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/core.py", line 4510, in set_index
        return set_index(
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/shuffle.py", line 189, in set_index
        divisions, mins, maxes = _calculate_divisions(
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/shuffle.py", line 40, in _calculate_divisions
        divisions, sizes, mins, maxes = base.compute(divisions, sizes, mins, maxes)
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/base.py", line 571, in compute
        results = schedule(dsk, keys, **kwargs)
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/threaded.py", line 79, in get
        results = get_async(
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/local.py", line 507, in get_async
        raise_exception(exc, tb)
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/local.py", line 315, in reraise
        raise exc
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/local.py", line 220, in execute_task
        result = _execute_task(task, data)
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/core.py", line 119, in _execute_task
        return func(*(_execute_task(a, cache) for a in args))
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/partitionquantiles.py", line 417, in percentiles_summary
        elif isinstance(data.dtype, pd.core.dtypes.dtypes.DatetimeTZDtype) or np.issubdtype(
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/numpy/core/numerictypes.py", line 419, in issubdtype
        arg1 = dtype(arg1).type
    TypeError: Cannot interpret 'Int64Dtype()' as a data type
    
    >>> ddf.compute().set_index('c')
         a  b
    c        
    1  NaN  1
    2  NaN  2
    
    >>> ddf.compute().dtypes
    a    object
    b     int64
    c     Int64
    dtype: object
  9. TomAugspurger commented on Feb 21, 2022

    @TomAugspurger
    Member

    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.

  10. jorloplaz commented on Mar 2, 2022

    @jorloplaz
    Contributor

    Actually, there seems to be an incompatibility in the very deep meta_from_array. This makes .values fail miserably, even when .compute() is not called. Perhaps it should be dtype.kind and not dtype itself that should be passed? @TomAugspurger :

    >>> ddf.dtypes
    a    object
    b     int64
    c     Int64
    dtype: object
    >>> ddf['c'].values
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/core.py", line 3105, in values
        split_every=split_every,
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/core.py", line 770, in map_partitions
        None as the division.
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/core.py", line 6139, in map_partitions
        for i, division in enumerate(divisions[:-1])
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/dataframe/core.py", line 7201, in new_dd_object
        """Does this object have a dask dataframe equivalent?"""
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/array/core.py", line 1217, in __new__
        This specifies the chunksize of your array blocks.
      File "/home/jorge.lopez/anaconda3/envs/AML/lib/python3.9/site-packages/dask/array/utils.py", line 57, in meta_from_array
        x = x(shape=(0,) * (ndim or 0), dtype=dtype)
    TypeError: Cannot interpret 'Int64Dtype()' as a data type
  11. TomAugspurger commented on Mar 2, 2022

    @TomAugspurger
    Member

    I'm not sure off hand. It might be worth seeing what we do with Categorical / CategoricalIndex.

  12. self-assigned this
    on Oct 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions