1

I have 2 dataframe the one looks like this :

      Date     id    name    amount    period   
2011-06-30      1       A     10000         1
2011-06-30      2       B     10000         1
2011-06-30      3       C     10000         1

And another one looks like this :

id   amount    period   
 1    10000         1
 3    10000         0

And the result that i want looks like this :

id     amount    period   
 1      20000         2
 2      10000         1
 3      20000         1

How can i do that in python pandas?

1 Answer 1

2

Use concat with filtered columns with aggregate sum:

df = pd.concat([df1[['id','amount','period']], df2]).groupby('id', as_index=False).sum()
print (df)
   id  amount  period
0   1   20000       2
1   2   10000       1
2   3   20000       1

EDIT:

If need subtract by id create index for id and then use DataFrame.sub:

df11 = df1[['id','amount','period']].set_index('id')
df22 = df2.set_index('id')

df3 = df11.sub(df22, fill_value=0).reset_index()
print (df3)
   id   amount  period
0   1      0.0     0.0
1   2  10000.0     1.0
2   3      0.0     1.0
Sign up to request clarification or add additional context in comments.

1 Comment

but how if i have other calculation like substract or whatever?

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.