Skip to content

Error using df.index in and condition #3227

Closed

Description

@postelrich

When trying to filter on the index and another condition I get a ValueError: 'dtype' inference failed in 'elemwise' error. The identical condition works in pandas. Issue seems related to the fact that df.index returns a dask array. On dask 0.17.1.

Example

import pandas as pd
import dask.dataframe as dd

df = pd.DataFrame({'time': pd.date_range('2018-01-01', periods=10),
                   'mycat': list('ABCABCABCA')})
df = df.set_index('time')
df['mycat'] = df.mycat.astype('category')
(df.index > '2018-01-01') & (df.mycat == 'A')

ddf = dd.from_pandas(df, npartitions=2)
(ddf.index > '2018-01-01') & (ddf.mycat == 'A')

Stacktrace

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-11ce8cc93904> in <module>()
      8 (df.index > '2018-01-01') & (df.mycat == 'A')
      9 ddf = dd.from_pandas(df, npartitions=2)
---> 10 (ddf.index > '2018-01-01') & (ddf.mycat == 'A')
     11 # (ddf.mycat == 'A') & (ddf.index > '2018-01-01')

~/anaconda3/envs/cme/lib/python3.6/site-packages/dask/array/core.py in __and__(self, other)
   1455 
   1456     def __and__(self, other):
-> 1457         return elemwise(operator.and_, self, other)
   1458 
   1459     def __rand__(self, other):

~/anaconda3/envs/cme/lib/python3.6/site-packages/dask/array/core.py in elemwise(op, *args, **kwargs)
   2935                 if not is_scalar_for_elemwise(a) else a
   2936                 for a in args]
-> 2937         dt = apply_infer_dtype(op, vals, {}, 'elemwise', suggest_dtype=False)
   2938         need_enforce_dtype = any(not is_scalar_for_elemwise(a) and a.ndim == 0 for a in args)
   2939 

~/anaconda3/envs/cme/lib/python3.6/site-packages/dask/array/core.py in apply_infer_dtype(func, args, kwargs, funcname, suggest_dtype)
    544         msg = None
    545     if msg is not None:
--> 546         raise ValueError(msg)
    547     return o.dtype
    548 

ValueError: `dtype` inference failed in `elemwise`.

Original error is below:
------------------------
AttributeError("'numpy.ndarray' object has no attribute 'index'",)

Traceback:
---------
  File "/Users/rpostelnik/anaconda3/envs/cme/lib/python3.6/site-packages/dask/array/core.py", line 529, in apply_infer_dtype
    o = func(*args, **kwargs)
  File "/Users/rpostelnik/anaconda3/envs/cme/lib/python3.6/site-packages/dask/dataframe/core.py", line 1706, in __array_wrap__
    index = context[1][0].index

Activity

  1. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member
  2. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member

    So I think we have two options that would make this work:

    1. Operations on dd.Index objects return other dd.Index or dd.Series objects (breaks with Pandas)
    2. We allow elementwise operations between dataframe and array objects if the array objects look like they might match (same number of partitions, unknown divisions) (somewhat unsafe)

    I'm inclined to try having operations on dd.Index objects return new dd.Index objects, though I suspect that this may uncover other cases where we've explicitly gone the other way.

    cc @TomAugspurger @jcrist any thoughts on the tradeoff above?

  3. TomAugspurger commented on Feb 28, 2018

    @TomAugspurger
    Member

    I think I would prefer option 2. What are the risks there, if we incorrectly guess that dask array object matches? I think that most (hopefully all?) operations would throw an exception at runtime if the lengths happened to not match.

  4. jcrist commented on Feb 28, 2018

    @jcrist
    Member

    I'm for option 1. We already do this in other places where pandas returns a numpy array (see my conversation with myself starting here for more information on why: #1877 (comment)).

  5. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member

    I think that most (hopefully all?) operations would throw an exception at runtime if the lengths happened to not match.

    If that's the case then I agree that option two sounds nice.

  6. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member

    Ah, @jcrist 's response narrowly beat mine. I'm happy to take a backseat on this decision if preferred. I suspect that both of you likely have more experience and thoughts on this than I do.

  7. jcrist commented on Feb 28, 2018

    @jcrist
    Member

    I think this is also a duplicate of #2195 (not an issue, just adding for link to historical conversation).

  8. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member

    it seems to me like we could reasonable support both solutions. Operations on Indexes can return Indexes. We can also support elementwise operations that mix arrays and dataframes.

  9. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member

    This complicates things:

    In [1]: import pandas as pd
    
    In [2]: import numpy as np
    
    In [3]: pd.Index(np.asarray([True, False]))
    Out[3]: Index([True, False], dtype='object')

    Pandas index objects don't support bool dtype?

  10. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member

    In particular this means that operations like ~(df.index > 1) become unpleasant

  11. jcrist commented on Feb 28, 2018

    @jcrist
    Member

    In particular this means that operations like ~(df.index > 1) become unpleasant

    Hmmm, it seems pandas indices don't support ~ in general:

    In [22]: ~pd.Index([1, 2, 3])
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-22-9bd6068b77be> in <module>()
    ----> 1 ~pd.Index([1, 2, 3])
    
    TypeError: bad operand type for unary ~: 'Int64Index'
    
    In [23]: ~pd.Index([True, False])
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-23-0b80ca766354> in <module>()
    ----> 1 ~pd.Index([True, False])
    
    TypeError: bad operand type for unary ~: 'Index'

    Options:

    • Return Series instead, with index set to match divisions of original index (as mentioned in the categorical PR). This allows our division aligning stuff to still work, and may be a better match for the kind of operations people do with numpy arrays. Downside is pandas often treats Series different than Index, especially in regard to alignment of operations. This may or may not pose issues.

    • Go with your option 2 above and just return a dask array with unknown shape. While I don't particularly like this, this may be a better fit overall.

  12. mrocklin commented on Feb 28, 2018

    @mrocklin
    Member

    First attempt at option one is here: #3229

  13. mrocklin commented on Mar 9, 2018

    @mrocklin
    Member

    Resolved by #3230

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions