How to create another column that contains an operation based on two different values of a same categorical column in a pandas dataframe?

Throwawayindi :

My data frame looks like this:

Person  Payment_Type   Amount  Place
Adam     C               500     X
Adam     D               200     X
Adam     C               80      Y
Adam     D               30      Y
Bob      C               100     Y
Bob      D               20      Y

I want to create a column Final_Payment such that it is equal to C-D for every place against every person. For example:

Person    Place    Final_Payment
Adam        X         300
Adam        Y         50
Bob         Y         80

Now, I've tried to groupby the Amount and the Place by writing:

sample=sample.groupby(['Place']).agg({'Amount':'sum'}) but this only gives me a dataframe with Places and the sum of all Amounts corresponding to it. I know this is wrong.

The logic that I've come up with so far is:

for Person, Place in Dataframe
   Final_Payment= Amount at C - Amount at D
end

and I honestly cannot figure out a way to code this part. How can I arrive at that final column against every place & person? I am really stumped at this point.

I'd genuinely appreciate any help I can get!

anky_91 :

You can pivot and then get the difference , then rename as you wish:

m = df.pivot_table(index=['Person','Place'],columns='Payment_Type',values='Amount')
out = (m['C']-m['D']).rename('Final_Payment').reset_index()

print(out)

  Person Place  Final_Payment
0   Adam     X          300.0
1   Adam     Y           50.0
2    Bob     Y           80.0

This is how the pivoted df looks like:

print(m)

Payment_Type    C    D
Person Place          
Adam   X      500  200
       Y       80   30
Bob    Y      100   20

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198630&siteId=1