Skip to content

dask groupby apply give weird indexes #3361

Closed

Description

@fl2o

Working with parquet files and pandas:

data = pd.read_parquet('./data.pq', engine='fastparquet', filters=[('day', 'in', [26,28])], index='index')
c = data.groupby('day')['time'].apply(lambda x : x.diff(1).dt.total_seconds().fillna(0))

Yield a series with index matching the initial dataframe

now with dask:

import dask.dataframe as dd
data = dd.read_parquet('./data.pq', engine='fastparquet', filters=[('day', 'in', [26,28])], index='index')
c = data.groupby('day')['time'].apply(lambda x : x.diff(1).dt.total_seconds().fillna(0), meta=pd.Series(dtype='uint8', name='diff')).compute()

yields a series with name=diff, dtype='float64' and indexes that don't match the initial data, neither range(0,n)... There is an argument 'index' in the meta pd.series but what I tried didn't give me the initial data indexes. The values are the same as before (with pandas), only index differs.

This is a problem because I am unable to do something like this

data = dd.read_parquet('./data.pq', engine='fastparquet', filters=[('day', 'in', [26,28])], index='index')
data['diff'] = data.groupby('day')['time'].apply(lambda x : x.diff(1).dt.total_seconds().fillna(0), meta=pd.Series(dtype='uint8', name='diff'))
data[['day', 'diff']].to_parquet('./data2.pq', partition_on = ['day'], engine='fastparquet', compression='UNCOMPRESSED')

because of bad indexes

Activity

  1. avlahop commented on Apr 2, 2018

    @avlahop
    Contributor

    I am having the same issue. It seems that using meta keywoard in apply of a grouped dataframe results in a false index in the _meta property of the dataframe, e.g

    @delayed
    def create_dataframe():
        return pd.DataFrame({'username': list('abcde') * 20, 'http_method': [random.choice(['GET', 'POST']) for i in range(100)], 'weekday': [np.random.randint(0, 7) for i in xrange(100)],'hour':[np.random.randint(0, 24) for i in xrange(100)], 'total_hits': [np.random.randint(0, 50) for i in range(100)]})
    
    dask_df = dd.from_delayed([create_dataframe() for i in range(5)])
    grouped = dask_df.groupby(['username', 'http_method', 'weekday', 'hour'])
    total_hits = grouped.total_hits.sum()
    total_hits.name = 'total_hits'
    total_hits = total_hits.reset_index()
    
    def combine_hours_total_hits(df):
        hours = df.hour.values
        total_hits = df.total_hits.values
        return np.vstack([hours, total_hits]).T.reshape(-1)
    
    total_hits_with_hours_grouped = total_hits.groupby(['username', 'http_method', 'weekday'])
    total_hits_combined = total_hits_with_hours_grouped.apply(combine_hours_total_hits, meta=('samples', np.dtype('O')))
    
    total_hits_combined._meta.index # this results RangeIndex(start=0, stop=0, step=1)

    Alternatively not using meta:

    total_hits_with_hours_grouped = total_hits.groupby(['username', 'http_method', 'weekday'])
    total_hits_combined = total_hits_with_hours_grouped.apply(combine_hours_total_hits)
    
    total_hits_combined._meta.index # this results MultiIndex(levels=[[u'foo'], [u'foo'], [1]], labels=[[], [], []], names=[u'username', u'http_method', u'weekday'])
  2. fl2o commented on Apr 5, 2018

    @fl2o
    Author

    update:
    Trying to compute intermediate results (with and w/o metadata) gives an error because of the indexes.

    data = dd.read_parquet('./data.pq', engine='fastparquet', filters=[('day', 'in', [26,28])], index=False)
    diff = data.groupby('Id')['time'].apply(lambda x: x.diff(1))
    

    diff.compute() yields "ValueError: cannot reindex from a duplicate axis"

    looking at the indexes of data:

    >> idx = data.index.compute()
    >> len(idx), idx.nunique()
    (2304742, 131231)
    
  3. TomAugspurger commented on Aug 8, 2019

    @TomAugspurger
    Member

    @FL20 DataFrameGroupBy.apply applies the user-provided function to each partition: https://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.groupby.DataFrameGroupBy.apply explains that better now I hope.

    It seems that using meta keywoard in apply of a grouped dataframe results in a false index in the _meta property of the dataframe, e.g

    Dask accepts things like meta=('samples', np.dtype('O')) as a shorthand for pd.Series(name='samples', dtype=object), which ash a RangeIndex. If you need the MultiIndex you'll need to specify that.

    Let me know if I missed anything.

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