Replace value in a specific with corresponding value

99封情书 提交于 2020-01-24 21:31:07

问题


I have a dataframe called REF with the following structure:

old_id  new_id
     3       6
     4       7
     5       8

I want to replace all the values that can be found equal to any of the old_id values in another dataframe NEW that is:

old_id  column_1  column_2
     3         a         e
     4         b         f
     9         c         g
     9         d         h

Therefore the new output dataset NEW will be:

old_id  column_1  column_2
     6         a         e
     7         b         f
     9         c         g
     9         d         h

回答1:


Use map:

s = df1.set_index('old_id')['new_id']

df2['old_id'] = df2['old_id'].map(s).fillna(df2['old_id'])

Or slowier solution with replace:

df2['old_id'] = df2['old_id'].replace(s)


来源:https://stackoverflow.com/questions/51022861/replace-value-in-a-specific-with-corresponding-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!