0

I have these two data frames df1 - have 5 rows

|id|name|age|weight|
|1 |aaaa|16 | 56   |
|2 |bbbb|17 | 60   |
|3 |cccc|18 | 56   |
|4 |dddd|16 | 61   |
|5 |ffff|20 | 75   |

df2 - also have 5 rows with same id but not sorted

|id|rate|
|5 |0.75|
|1 |0.80|
|3 |0.92|
|4 |0.86|
|2 |0.77|

now I need to merge them to be like this df3

|id|name|age|weight|rate|
|1 |aaaa|16 | 56   |0.80|
|2 |bbbb|17 | 60   |0.77|
|3 |cccc|18 | 56   |0.92|
|4 |dddd|16 | 61   |0.86|
|5 |ffff|20 | 75   |0.75|

thanks in advance

Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Does this answer your question? [Pandas merge two dataframes with different columns](https://stackoverflow.com/questions/28097222/pandas-merge-two-dataframes-with-different-columns) – vladsiv Nov 27 '21 at 12:08

3 Answers3

1

If you have a df_1 similar to this:

   id name  col1
0   1  foo    42
1   2  bar    43

and df_2 similar to this:

   id  rate
0   2    -1
1   1     1

you can use the join method from pandas (doc):

df_1.join(df_2.set_index("id"), on="id") which gives

   id name  col1  rate
0   1  foo    42     1
1   2  bar    43    -1
Antoine Redier
  • 395
  • 1
  • 8
1

I would advise you to use the merge function using pandas. It'll allow you to specify the the type of join you want to perform on the two dataframes.

pd.merge(left = first_dataframe, right = second_dataframe, how = 'specify the type of join here like left, right, inner etc..', on = 'specify the column here')

Here's some documentation that you can use to refer the merge function. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html

adist98
  • 49
  • 10
0

Use merge:

>>> df1.merge(df2, on='id')
   id  name  age  weight  rate
0   1  aaaa   16      56  0.80
1   2  bbbb   17      60  0.77
2   3  cccc   18      56  0.92
3   4  dddd   16      61  0.86
4   5  ffff   20      75  0.75

Read Pandas Merging 101

Corralien
  • 109,409
  • 8
  • 28
  • 52