Skip to content

dataframe.percentiles_summary cannot handle pandas "string" data type #8779

Closed

Description

@scharlottej13

Noticed this when answering this question on Stack Overflow, percentiles_summary, which is used to set new partition divisions for shuffle operations, does not know how to handle pandas "string" data types.

What happened:
The following snippet produces TypeError: Cannot interpret 'string[python]' as a data type:

import pandas as pd
import dask.dataframe as dd
                                                                    
data = {"calories": [420, "hi", 390], "duration": [50, 40, 45]}                               
df = pd.DataFrame(data)                                          
ddf = dd.from_pandas(df, npartitions=2)

ddf = ddf.astype({"calories": "string"}).set_index('calories')
Full traceback:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/hf/2s7qjx7j5ndc5220_qxv8y800000gn/T/ipykernel_81716/3824196896.py in <module>
      6 ddf = dd.from_pandas(df, npartitions=2)
      7 
----> 8 ddf = ddf.astype({"calories": "string"}).set_index('calories')

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/dask/dataframe/core.py in set_index(***failed resolving arguments***)
   4607             from .shuffle import set_index
   4608 
-> 4609             return set_index(
   4610                 self,
   4611                 other,

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/dask/dataframe/shuffle.py in set_index(df, index, npartitions, shuffle, compute, drop, upsample, divisions, partition_size, **kwargs)
    213 
    214     if divisions is None:
--> 215         divisions, mins, maxes = _calculate_divisions(
    216             df, index2, repartition, npartitions, upsample, partition_size
    217         )

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/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:

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/dask/base.py in compute(traverse, optimize_graph, scheduler, get, *args, **kwargs)
    571         postcomputes.append(x.__dask_postcompute__())
    572 
--> 573     results = schedule(dsk, keys, **kwargs)
    574     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    575 

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/dask/threaded.py in get(dsk, result, cache, num_workers, pool, **kwargs)
     79             pool = MultiprocessingPoolExecutor(pool)
     80 
---> 81     results = get_async(
     82         pool.submit,
     83         pool._max_workers,

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/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)
    504                             _execute_task(task, data)  # Re-execute locally
    505                         else:
--> 506                             raise_exception(exc, tb)
    507                     res, worker_id = loads(res_info)
    508                     state["cache"][key] = res

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/dask/local.py in reraise(exc, tb)
    312     if exc.__traceback__ is not tb:
    313         raise exc.with_traceback(tb)
--> 314     raise exc
    315 
    316 

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)
    217     try:
    218         task, data = loads(task_info)
--> 219         result = _execute_task(task, data)
    220         id = get_id()
    221         result = dumps((result, id))

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/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

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/site-packages/dask/dataframe/partitionquantiles.py in percentiles_summary(df, num_old, num_new, upsample, state)
    415         data = data.cat.codes
    416         interpolation = "nearest"
--> 417     elif isinstance(data.dtype, pd.core.dtypes.dtypes.DatetimeTZDtype) or np.issubdtype(
    418         data.dtype, np.integer
    419     ):

~/mambaforge/envs/dask-mini-tutorial/lib/python3.9/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 'string[python]' as a data type

What you expected to happen:
This works if you use str instead:

import pandas as pd
import dask.dataframe as dd
                                                                    
data = {"calories": [420, "hi", 390], "duration": [50, 40, 45]}                               
df = pd.DataFrame(data)                                          
ddf = dd.from_pandas(df, npartitions=2)

ddf = ddf.astype({"calories": str}).set_index('calories')

and also works in pandas:

import pandas as pd
                                                                    
data = {"calories": [420, "hi", 390], "duration": [50, 40, 45]}                               
df = pd.DataFrame(data)                                          
df = df.astype({"calories": "string"}).set_index("calories")

Anything else we need to know?:

Environment:

  • Dask version: 2022.02.1
  • pandas version: 1.4.0
  • Python version: 3.9
  • Operating System: MacOS
  • Install method (conda, pip, source):

Activity

  1. added
    needs triage
    on Mar 4, 2022
  2. added
    bug
    and removed
    needs triage
    on Mar 4, 2022
  3. scharlottej13 commented on Mar 9, 2022

    @scharlottej13
    ContributorAuthor

    closing, will address this issue in #8788

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

    bugdataframe

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions