Issue
Let me explain the structure of the problem that I'm trying to solve. Let's suppose that we have two dataframes
DF1:
ID | Value |
---|---|
AA | 2 |
AB | 1 |
AC | 2 |
AD | 1 |
AE | 2 |
DF2:
ID | New Value |
---|---|
AA | 1 |
AC | 1 |
If the ID column row in DF1 is in DF2, then I would like to change the value in the same row in DF1 to the one that it has in DF2, so the end result would be something like this:
DF1:
ID | Value |
---|---|
AA | 1 |
AB | 1 |
AC | 1 |
AD | 1 |
AE | 2 |
So far, I have tried attempts with .loc and np.where but none of them where successful, my closest attempt is the following line of code:
DF1['Value'][row] = [DF2['New Value'][row] if ((DF1['ID'][row]).isin(DF2['ID'])) else DF1['Value'][row] for row in DF['ID']]
Solution
here is one way to to do it using map
# set index on ID in DF2 and map to DF
# replace failed mapping with the value in DF
df['Value']=df['ID'].map(df2.set_index(['ID'])['New Value']).fillna(df['Value'])
df
ID Value
0 AA 1.0
1 AB 1.0
2 AC 1.0
3 AD 1.0
4 AE 2.0
Answered By - Naveed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.