AHAD
AHAD

Reputation: 239

How change values in dataframe based on another in pandas?

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.

Upvotes: 2

Views: 63

Answers (1)

AChampion
AChampion

Reputation: 30288

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()

Upvotes: 4

Related Questions