0

Considering two Pandas dataframes:

df1:

name    key
a       0
b       1
c       0
d       0
e       1

df2:

key     value_1     value_2
0       11          12
0       21          22
1       111         112
1       121         122
1       131         132

How to obtain a new tidy Pandas dataframe df3 that inserts in df1 the values of df2 selected in function of the values in the column type of df1 and df2:

df3:

name    key     value_1     value_2 
a       0       11          12
a       0       21          22
b       1       111         112
b       1       121         122
b       1       131         132
c       0       11          12
c       0       21          22
d       0       11          12
d       0       21          22
e       1       111         112
e       1       121         122
e       1       131         132
cmg
  • 1
  • 1
  • Welcome to [Stack Overflow](https://stackoverflow.com/tour). Please check [How to Ask](https://stackoverflow.com/help/how-to-ask). It's also best to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to enable others to help you. And check [How to make pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – MagnusO_O Oct 15 '22 at 15:29

1 Answers1

1

Merge pandas dataframes

We can perform joins on your two pandas dataframes df1 and df3.

df3 = pd.merge(df1, df2, how='inner', left_on=['key'], right_on = ['key'])

We can write it more concisely this way

df3 = pd.merge(df1, df2, how='inner', on=['key'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

SRJ
  • 2,092
  • 3
  • 17
  • 36