Skip to content

Bug with delayed head-method for pandas string columns #7206

Open

Description

@jborchma

What happened:

So I stumbled upon a very random bug. Essentially, when running the head-method with delayed execution on a dask Series with the pandas string type, I stumble upon this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-a1acb387bb63> in <module>
----> 1 test = dask_df["d"].head(compute=False).values

~/opt/miniconda3/envs/wiyd/lib/python3.8/site-packages/dask/dataframe/core.py in values(self)
   2739         will not work.
   2740         """
-> 2741         return self.map_partitions(methods.values)
   2742 
   2743     def _validate_chunks(self, arr, lengths):

~/opt/miniconda3/envs/wiyd/lib/python3.8/site-packages/dask/dataframe/core.py in map_partitions(self, func, *args, **kwargs)
    676         None as the division.
    677         """
--> 678         return map_partitions(func, self, *args, **kwargs)
    679 
    680     @insert_meta_param_description(pad=12)

~/opt/miniconda3/envs/wiyd/lib/python3.8/site-packages/dask/dataframe/core.py in map_partitions(func, meta, enforce_metadata, transform_divisions, *args, **kwargs)
   5460 
   5461     graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
-> 5462     return new_dd_object(graph, name, meta, divisions)
   5463 
   5464 

~/opt/miniconda3/envs/wiyd/lib/python3.8/site-packages/dask/dataframe/core.py in new_dd_object(dsk, name, meta, divisions)
   6499                 for i in range(len(chunks[0])):
   6500                     layer[(name, i) + suffix] = layer.pop((name, i))
-> 6501         return da.Array(dsk, name=name, chunks=chunks, dtype=meta.dtype)
   6502     else:
   6503         return get_parallel_type(meta)(dsk, name, meta, divisions)

~/opt/miniconda3/envs/wiyd/lib/python3.8/site-packages/dask/array/core.py in __new__(cls, dask, name, chunks, dtype, meta, shape)
   1114         self.dask = dask
   1115         self.name = str(name)
-> 1116         meta = meta_from_array(meta, dtype=dtype)
   1117 
   1118         if (

~/opt/miniconda3/envs/wiyd/lib/python3.8/site-packages/dask/array/utils.py in meta_from_array(x, ndim, dtype)
     68 
     69     if isinstance(x, type):
---> 70         x = x(shape=(0,) * (ndim or 0), dtype=dtype)
     71 
     72     if (

TypeError: Cannot interpret 'StringDtype' as a data type

So what fails? (See full example below):

dask_df["d"].head(compute=False).values

Interestingly enough, running the delayed head-method on the whole dataframe works, so there must be a connection to Series with this bug. Also running the above statement without values works fine too:

dask_df.head(compute=False).values
dask_df["d"].head(compute=False)

What you expected to happen:
I would expect the behaviour to not error out and show the values when computed.

Minimal Complete Verifiable Example:

import dask.dataframe as dd
import pandas as pd

df = pd.DataFrame.from_dict(
    {
        "d": ["a", "aa", "v", "aa", "aa", "aa"],
    }
)
df["d"] = df["d"].astype("string")
dask_df = dd.from_pandas(df, npartitions=2)

test = dask_df["d"].head(compute=False).values

Environment:

  • Dask version: 2021.02.0
  • Python version: 3.8.6
  • Operating System: MacOS
  • Install method (conda, pip, source): pip

Activity

  1. TomAugspurger commented on Feb 11, 2021

    @TomAugspurger
    Member

    Is the .values necessary to trigger the bug? There's another issue with .values causing issues with extension arrays.

  2. jborchma commented on Feb 12, 2021

    @jborchma
    ContributorAuthor

    Is the .values necessary to trigger the bug? There's another issue with .values causing issues with extension arrays.

    Yeah, dask_df["d"].head(compute=False) doesn't error.

  3. gjoseph92 commented on Mar 12, 2021

    @gjoseph92
    Collaborator

    So this doesn't have anything to do with head(); in fact, it's just about .values on a delayed Series where the dtype is a pandas extension dtype:

    import dask.dataframe as dd
    import pandas as pd
    
    s = pd.Series(["foo"], dtype="string")
    dd.from_pandas(s, 1).values
    # same TypeError: Cannot interpret 'StringDtype' as a data type

    When constructing the dask Array's meta object, we're currently assuming the underlying array type is a NumPy array, when in this case, it's actually going to be a pandas StringArray. But unlike pandas, NumPy doesn't know how to handle a StringDtype.

    I'll push up a potential fix for this in a moment.

  4. devyzr commented on Apr 8, 2021

    @devyzr

    I'm getting a similar error when using a string column as an index for set_index on a DataFrame:

    TypeError: Cannot interpret 'StringDtype' as a data type

    My code is basically the following:

    dataframe = dd.read_csv(file_path, dtype={"colName": "string"}, blocksize=100e6)
    dataframe.set_index("colName")
    

    And my pip freeze file is the following:

    cloudpickle==1.6.0
    dask==2021.4.0
    docopt==0.6.2
    fsspec==0.9.0
    locket==0.2.1
    numpy==1.20.2
    pandas==1.2.3
    partd==1.1.0
    pycodestyle==2.7.0
    python-dateutil==2.8.1
    pytz==2021.1
    PyYAML==5.4.1
    six==1.15.0
    toml==0.10.2
    toolz==0.11.1
    

    Is this a bug or expected behavior? Changing the index to an object type solved my issue.

  5. dhirschfeld commented on Aug 8, 2021

    @dhirschfeld

    I have pd.DataFrame with string columns and am hitting this bug when simply trying to convert it to a dask dataframe:

    >>> df = dd.from_pandas(packed_data, npartitions=1).set_index('Reference')
    Traceback (most recent call last):
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\IPython\core\magics\execution.py", line 1321, in time
        exec(code, glob, local_ns)
      File "<timed exec>", line 1, in <module>
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\dataframe\core.py", line 4249, in set_index
        **kwargs,
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\dataframe\shuffle.py", line 163, in set_index
        df, index2, repartition, npartitions, upsample, partition_size
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\dataframe\shuffle.py", line 35, in _calculate_divisions
        divisions, sizes, mins, maxes = base.compute(divisions, sizes, mins, maxes)
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\base.py", line 568, in compute
        results = schedule(dsk, keys, **kwargs)
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\threaded.py", line 87, in get
        **kwargs
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\local.py", line 514, in get_async
        raise_exception(exc, tb)
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\local.py", line 325, in reraise
        raise exc
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\local.py", line 223, in execute_task
        result = _execute_task(task, data)
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\core.py", line 121, in _execute_task
        return func(*(_execute_task(a, cache) for a in args))
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\dask\dataframe\partitionquantiles.py", line 416, in percentiles_summary
        elif np.issubdtype(data.dtype, np.integer) and not is_cupy_type(data):
      File "C:\Users\dhirschf\envs\dev\lib\site-packages\numpy\core\numerictypes.py", line 419, in issubdtype
        arg1 = dtype(arg1).type
    TypeError: Cannot interpret 'StringDtype' as a data type

    In my case it looks like it's casting to numpy with .values here:

    data = df.values

  6. jorloplaz commented on Feb 24, 2022

    @jorloplaz
    Contributor

    This is similar to what we're discussing in #5720 . The problem appears to be in partitionquantiles.py, which thinks that numpy dtypes are being used, instead of extended Pandas ones. However, I'm not sure about how to proceed.

  7. added
    needs attention
    on Nov 18, 2024
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