0

How can I update a column when I have the values with their corresponding index? Without iterating.

df1:

   index_copy  Numeric Value
0          63   7.999600e+07
1          64   8.333368e+07
2          70   3.999600e+07
3          71   7.333368e+07
4          77   2.999600e+07

Into another dataframe column with empty values. In this case I want to add the values at index 63, 64, 70, 71 and 77.

df2['Column_to_be_updated']:

        Column_to_be_updated
0       NaN
1       NaN
2       NaN
3       NaN
4       NaN
Gorgonzola
  • 363
  • 3
  • 11

1 Answers1

0

You could do something like df2.join(df1.set_index('index_copy'), on=df2.index), where set_index sets the index of df1 to the values in the column "index_copy", and then we join on the indexes.

Update: what mozway suggested was better:

df1 = pd.DataFrame({
    'index': [63, 64, 70, 71, 72],
    'Numeric Value': [7.999600e+07, 8.333368e+07, 3.999600e+07, 7.333368e+07, 2.999600e+07]
})

df2 = pd.DataFrame({
    'Numeric Value': [np.nan for i in range(100)]
})

df2.merge(df1, left_index=True, right_on='index', how='left')
Mark
  • 7,785
  • 2
  • 14
  • 34
  • I got KeyError: RangeIndex(start=0, stop=9140, step=1). "Column_to_be_updated" have the same column name on both dfs. How does the join know where to update in this case? – Gorgonzola Jul 13 '23 at 16:50
  • @Gorgonzola check update! – Mark Jul 13 '23 at 17:11