Skip to content

Behaviour of map_partitions with a Pandas dataframe as argument - In this case uncorrect merge #6357

Closed

Description

@odovad

I want to perform a merge between a Dask dataframe and a Pandas Dataframe and it seems like the pandas dataframe I pass as argument is partitionned in a way that it does not give the result we expect in the end.
I wanted to be able to able to keep the index on the Dask Dataframe, that's why I tried to use a map_partitions instead of a merge on the Dask Dataframe directly.

I think the reason of this behaviour is explained by "DataFrame-like args (both dask and pandas) will be repartitioned to align (if necessary) before applying the function." in the API documentation.

food_stores = pd.DataFrame({'foodstore_id':[1,2,3], 
                            'seller_firstname':['Bob', 'Alice', 'Monique'], 
                            'seller_lastname':['Marchand', 'Boul', 'Mul'],  
                            'online_status':[1,1,0]})
records = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10], 
                        'name':['product1', 'product2', 'product3', 'product4', 'product5', 
                                'product6', 'product7', 'product8', 'product9', 'product10'],
                        'seller_firstname':['Bob', 'Alice', 'Monique', 'Alice', 'Bob', 
                                            'Alice', 'Monique', 'Bob', 'Alice', 'Bob'],
                        'seller_lastname':['Marchand', 'Boul', 'Mul', 'Boul', 'Marchand', 
                                           'Boul', 'Mul', 'Marchand', 'Boul', 'Marchand'],
                        })
records = records.set_index('id')
records = dd.from_pandas(records, npartitions=3)

def mapping(part, pandas_df):
    pandas_df = pandas_df.set_index(['seller_firstname', 'seller_lastname'])    
    return part.merge(pandas_df, how='left', 
                      left_on=['seller_firstname', 'seller_lastname'], 
                      right_on=['seller_firstname', 'seller_lastname'], right_index=True)

print(records.map_partitions(mapping, food_stores).compute())
id name seller_firstname seller_lastname foodstore_id online_status
1 product1 Bob Marchand nan nan
2 product2 Alice Boul nan nan
3 product3 Monique Mul 3 0
4 product4 Alice Boul nan nan
5 product5 Bob Marchand nan nan
6 product6 Alice Boul nan nan
7 product7 Monique Mul nan nan
8 product8 Bob Marchand nan nan
9 product9 Alice Boul nan nan
10 product10 Bob Marchand nan nan

I thought I would get the result I expect with the following :

food_stores = pd.DataFrame({'foodstore_id':[1,2,3], 
                            'seller_firstname':['Bob', 'Alice', 'Monique'], 
                            'seller_lastname':['Marchand', 'Boul', 'Mul'],  
                            'online_status':[1,1,0]})
records = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10], 
                        'name':['product1', 'product2', 'product3', 'product4', 'product5', 
                                'product6', 'product7', 'product8', 'product9', 'product10'],
                        'seller_firstname':['Bob', 'Alice', 'Monique', 'Alice', 'Bob', 'Alice', 
                                            'Monique', 'Bob', 'Alice', 'Bob'],
                        'seller_lastname':['Marchand', 'Boul', 'Mul', 'Boul', 'Marchand', 'Boul', 
                                           'Mul', 'Marchand', 'Boul', 'Marchand'],
                        })
records = records.set_index('id')
records = dd.from_pandas(records, npartitions=3)

def mapping(part, pandas_df):
    pandas_df = pandas_df.set_index(['seller_firstname', 'seller_lastname'])    
    return part.merge(pandas_df, how='left', left_on=['seller_firstname', 'seller_lastname'], right_on=['seller_firstname', 'seller_lastname'], right_index=True)

records.map_partitions(lambda part: mapping(part, food_stores)).compute()
id name seller_firstname seller_lastname foodstore_id online_status
1 product1 Bob Marchand 1 1
2 product2 Alice Boul 2 1
3 product3 Monique Mul 3 0
4 product4 Alice Boul 2 1
5 product5 Bob Marchand 1 1
6 product6 Alice Boul 2 1
7 product7 Monique Mul 3 0
8 product8 Bob Marchand 1 1
9 product9 Alice Boul 2 1
10 product10 Bob Marchand 1 1

Environment:

  • Dask version: 2.16.0 (same with latest - 2.19)
  • Python version: 3.7.3
  • Operating System: Ubuntu 18.04.3 LTS
  • Install method (conda, pip, source): image daskdev/dask-notebook 2.16.0

Activity

  1. TomAugspurger commented on Jun 30, 2020

    @TomAugspurger
    Member

    I'm not sure about the expected behavior here, but right now your bet is to disable the alignment of the pandas DataFrame by passing it as a keyword

    res = records.map_partitions(mapping, pandas_df=food_stores).compute()
    

    FYI, since you're adjusting the index you should also call clear_divisions() on the result.

  2. mrocklin commented on Jun 30, 2020

    @mrocklin
    Member
  3. odovad commented on Jun 30, 2020

    @odovad
    Author

    Thanks @TomAugspurger, I did not try this way. I think the behaviour is not easy to understand.
    Why is the pandas DataFrame aligned ?

    What do you mean when you say I'm adjusting the index ?
    The number of lines did not change, only two columns are added.
    It's not safe to say that we can trust the index?
    We need to "reindex" if we want to be able to use the index effectively ?

  4. odovad commented on Jun 30, 2020

    @odovad
    Author

    @mrocklin On one partition, it seems to work well :
    Do you think the map_partitions as defined here can break the index ?

    print(mapping(records.partitions[0].compute(), food_stores).to_markdown())
    id name seller_firstname seller_lastname foodstore_id online_status
    1 product1 Bob Marchand 1 1
    2 product2 Alice Boul 2 1
    3 product3 Monique Mul 3 0
    4 product4 Alice Boul 2 1
  5. TomAugspurger commented on Jun 30, 2020

    @TomAugspurger
    Member

    I think this demonstrates the issue a bit more clearly

    import pandas as pd
    import dask.dataframe as dd
    
    df1 = pd.DataFrame({"A": [1, 2, 3, 3, 2, 3], "B": [1, 2, 3, 4, 5, 6]})
    df2 = pd.DataFrame({"A": [3, 1, 2], "C": [1, 2, 3]})
    
    
    def merge(a, b):
        res = pd.merge(a, b, left_on="A", right_on="A", how="left")
        return res
    
    
    res_pandas = merge(df1, df2)
    res_dask = dd.from_pandas(df1, npartitions=2).map_partitions(merge, df2)
    In [18]: res_pandas
    Out[18]:
       A  B  C
    0  1  1  2
    1  2  2  3
    2  3  3  1
    3  3  4  1
    4  2  5  3
    5  3  6  1
    
    In [19]: res_dask.compute()
    Out[19]:
       A  B    C
    0  1  1  2.0
    1  2  2  NaN
    0  3  3  NaN
    0  3  4  NaN
    1  2  5  NaN
    2  3  6  NaN
  6. odovad commented on Jun 30, 2020

    @odovad
    Author

    @TomAugspurger and the result is not the same depending on the number of partitions you choose

    Can you give more detail about the indexation ?
    Why a clear_divisions() is needed ?
    (I wanted to be able not to break the index ... maybe there is a way ?)

  7. TomAugspurger commented on Jun 30, 2020

    @TomAugspurger
    Member
  8. odovad commented on Jun 30, 2020

    @odovad
    Author

    Ok @TomAugspurger. Thanks. I was interested; I thought you said I managed to be in a situation where the dataframe has an index with known divisions that we cannot trust. Interesting to know since a set_index on a large dataframe is something we want to avoid.

  9. jsignell commented on Sep 11, 2020

    @jsignell
    Member

    This is an interesting issue because in the dask code we assume that a pandas dataframe should be treated like a dask dataframe and partitioned before doing the operation, but in this case you are using df2 more as a lookup table. I changed @TomAugspurger's example to use a dict instead and it works as expected.

    import pandas as pd
    import dask.dataframe as dd
    
    df1 = pd.DataFrame({"A": [1, 2, 3, 3, 2, 3], "B": [1, 2, 3, 4, 5, 6]})
    d2 = {"A": [3, 1, 2], "C": [1, 2, 3]}
    
    
    def merge(a, b):
        res = pd.merge(a, pd.DataFrame(b), left_on="A", right_on="A", how="left")
        return res
    
    
    res_pandas = merge(df1, pd.DataFrame(d2))
    res_dask = dd.from_pandas(df1, npartitions=2).map_partitions(merge, d2)

    The issue is how to know the user's intentions. When you pass a pandas dataframe as an argument to map_partitions just passing it in to each function makes a lot of sense. But making that change now might break people. I think it would require a new kwarg see #6628

    Another option is to user a kwarg in your map_partitions func rather than an arg:

    import pandas as pd
    import dask.dataframe as dd
    
    df1 = pd.DataFrame({"A": [1, 2, 3, 3, 2, 3], "B": [1, 2, 3, 4, 5, 6]})
    df2 = pd.DataFrame({"A": [3, 1, 2], "C": [1, 2, 3]})
    
    
    def merge(a, lookup=None):
        res = pd.merge(a, lookup, left_on="A", right_on="A", how="left")
        return res
    
    res_pandas = merge(df1, df2)
    
    ddf1 = dd.from_pandas(df1, npartitions=2)
    res_dask = ddf1.map_partitions(merge, lookup=df2)
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions