2

Hi, i have two dataframes and i want to change values in first dataframe where have same IDs in both dataframes, suppose i have:

df1 = [ID  price
       1     200
       4     300
       5     120
       7     230
       8     110
       9     90
       12    180]

and

df2 = [ID    price   count
       3       340     27
       4       60      10
       5       290     2]

after replace:

df1 = [ID  price
       1     200
       4     60
       5     290
       7     230
       8     110
       9     90
       12    180]

my first try:

df1.loc[df1.ID.isin(df2.ID),['price']] = df2.loc[df2.ID.isin(df1.ID),['price']].values

but it isn't correct.

0

1 Answer 1

4

Assuming ID is the index (or can be set as the index), then you can just update:

In []:
df1.update(df2)
df1

Out[]:
    price
ID       
1   200.0
4    60.0
5   290.0
7   230.0
8   110.0
9    90.0
12  180.0

If you need to set_index():

df = df1.set_index('ID')
df.update(df2.set_index('ID'))
df1 = df.reset_index()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.