Create duplicate values when combining dataframes

Viewed 25

I have 2 dataframes like so:

df1

Name Animal
John Dog
John Cat
John Horse
Mary Dog
Mary Cat
Mary Horse

df2

Name Color
John Blue
Mary Red

I would like to merge them such that:

df3

Name Animal Color
John Dog Blue
John Cat Blue
John Horse Blue
Mary Dog Red
Mary Cat Red
Mary Horse Red

What would be the clearest way to go about this? I've tried multiple permutations of concat(), append(), merge(), and join() functions to no avail. I'm sure it has to be something simple, but most of the literature around this focuses on subsetting and eliminating duplicates, but not adding them.

1 Answers
df['Color'] = df['Name'].map(df2.set_index(['Name'])['Color'])
    Name    Animal  Color
0   John    Dog     Blue
1   John    Cat     Blue
2   John    Horse   Blue
3   Mary    Dog     Red
4   Mary    Cat     Red
5   Mary    Horse   Red
Related