3

I have following DataFrames:

    stores = [['AA', 12, 'Red'], ['BB', 13, 'Red'], ['BB', 14, 'Red'], ['BB', 15, 'Red']]
    visits = [['BB', 13, 'Green'], ['BB', 14, 'Blue']]

    stores_df = pd.DataFrame(data=stores, columns=['retailer', 'store', 'color'])
    stores_df.set_index(['retailer', 'store'], inplace=True)

    visits_df = pd.DataFrame(data=visits, columns=['retailer', 'store', 'color'])
    visits_df.set_index(['retailer', 'store'], inplace=True)

                color
retailer store       
BB       13     Green
         14      Blue

               color
retailer store      
AA       12      Red
BB       13      Red
         14      Red
         15      Red

How I can merge them in order to get following result:

               color
retailer store      
AA       12      Red
BB       13      Green
         14      Blue
         15      Red

2 Answers 2

3

You can use update:

In [41]: stores_df.update(visits_df)

In [42]: stores_df
Out[42]:
                color
retailer store
AA       12       Red
BB       13     Green
         14      Blue
         15       Red
Sign up to request clarification or add additional context in comments.

3 Comments

This is a great answer. update changes inplace and does not have a return value. These are features that can be useful. +1
I actually prefer much more combine_first. Changing inplace and no return is stabbing you in your back. I am far more keen on a functional paradigm where you do not modify the object and you have a return value: a copy of the object, modified.
True and I agree. But I wasn't aware of an update on dataframes. I'll keep it in mind for potential future use.
2

You want to use combine_first

visits_df.combine_first(stores_df)

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.