0

I have two dataframe:

df_1 = pd.DataFrame({'code_1': ['aaa', 'bbb', 'aaa', 'ddd', '', 'bbb'],
                     'code_2': ['','','','','',''],
                     'other_1': [11, 7, 8, 10, 13, 13],
                     'other_2': [5, 7, 7, 9, 12, 9]})
(out)>>>
    code_1 code_2  other_1  other_2
0    aaa              11        5
1    bbb               7        7
2    aaa               8        7
3    ddd              10        9
4                     13       12
5    bbb              13        9

df_2 = pd.DataFrame({'Name': ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff'],
                     'extra' : ['red', 'blue', 'green', 'yellow', 'pink', 'orange']})
(out)>>>
   Name   extra
0  aaa     red
1  bbb    blue
2  ccc   green
3  ddd  yellow
4  eee    pink
5  fff  orange

I would like to fill the column "code_2" of df_1 with the names in "extra" of df_2, but only if "code_1" of df_1 is equal to "Name" of df_2. Like:

    code_1  code_2  other_1  other_2
0    aaa     red       11        5
1    bbb    blue        7        7
2    aaa     red        8        7
3    ddd  yellow       10        9
4                      13       12
5    bbb    blue       13        9

How can I do?

Mario
  • 89
  • 6
  • 1
    This was closed while I was trying to solve it, I leave my code here, although it could probably be improved using pd.merge: `for i, row in df_2.iterrows(): df_1["code_2"].where(df_1["code_1"] != row["Name"], row["extra"], inplace=True)` – Iñigo Moreno Sep 28 '22 at 10:48

0 Answers0