Adhil
Adhil

Reputation: 1858

How to add Column Values from 2nd DataFrame Based on Some Column Values in First dataframe in Pandas

My 1st DataFrame is so:

RowCol  Value_Pre
Key1 234
Key3 235
Key2 235
Key4 237

My Second Dataframe is:

RowCol  Value_Post
Key3 235
Key1 334
Key4 237
Key2 435

How to create a third dataframe like a the one below by combining the two dataframe

RowCol  Value_Pre Value_Post
Key1 	234	334
Key3	235	235
Key2	235	435
Key4	237	237

How to develop this code in Python?

Upvotes: 1

Views: 46

Answers (1)

jezrael
jezrael

Reputation: 862431

Use map:

df1['Value_Post'] = df1['RowCol'].map(df2.set_index('RowCol')['Value_Post'])
print (df1)
  RowCol  Value_Pre  Value_Post
0   Key1        234         334
1   Key3        235         235
2   Key2        235         435
3   Key4        237         237

Or merge with left join, especially if necessary append multiple new columns:

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

Upvotes: 1

Related Questions