matching pairs of positive and negative numbers for every id

  dataframe, dictionary, pandas, python, python-3.x

I have the dataframe below:

import pandas as pd
d = {'id': [1,1,2,2,3,3,3,4,4],
    'amount':[2,3,5,-5,2,3,-5,3,4]}

d = pd.DataFrame(d)
d
   id   amount
0   1   2
1   1   3
2   2   5
3   2   -5
4   3   2
5   3   3
6   3   -5
7   4   3
8   4   4

So what i want to do, is match the positive with the negative values per id and i do this:

d[d.groupby(['id'])['amount'].transform('sum').eq(0)

which gives me this output:


   id   amount
2   2   5
3   2   -5
4   3   2
5   3   3
6   3   -5

So as you can see my code does not only matches pairs of rows as i want. For instance, for id 3, it matches three rows on the condition i’ve set. How can i get it to only match pairs of rows and have the desired output as the one below:

   id   amount
2   2   5
3   2   -5

Source: Python-3x Questions

LEAVE A COMMENT