Lostsoul
Lostsoul

Reputation: 26017

How can I merge Pandas DF and maintain merged structure?

I'm not quite sure how to explain my problem so I'll just describe it.

DF1
      Name  Year
0   foo  2020
1   bar  2020
2   foo  2019
3   foo  2018

DF2
Name Value
foo  A
bar  A
bar  B

When I merge it, I want:

      Name  Year Value
  foo  2020  A
  bar  2020  A
  bar  2020  B
  foo  2019  A
  foo  2018  A

Basically, if df2 has multiple entries for a value(in this case bar then it should create two entries for it).

Right now I'm just getting one result per row by doing this:

df1['value']=df1[['Name']].merge(df2,how='right').value

Upvotes: 2

Views: 35

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

I think you mean how='left' not how='right':

df1.merge(df2, on='Name', how='left')

Output:

  Name  Year Value
0  foo  2020     A
1  bar  2020     A
2  bar  2020     B
3  foo  2019     A
4  foo  2018     A

Upvotes: 3

Related Questions