3
    A   B
0   1  12
1   1  13
2   1  15
3   2  16
4   2  19
5   2  20
6   3  32
7   3  29
8   3  25
9   4   3
10  4   5
11  4   7

I have a pandas dataframe as shown above.I want to group column 'A' by values like 1 2 3 4 and subtract the values of column B of all the groups from group 4. How can I do it?

My result should look like:

    
A   B   C
1   12  9
1   13  8
1   15  8
2   16  13
2   19  14
2   20  13
3   32  29
3   29  24
3   25  18
4   3   0
4   5   0
4   7   0
5

You can use groupby and apply. To get the group for A=4, call GroupBy.get_group(4).

g = df.groupby('A')
df['C'] = g.apply(lambda x: x['B'] - g.get_group(4)['B'].values).values
df

    A   B   C
0   1  12   9
1   1  13   8
2   1  15   8
3   2  16  13
4   2  19  14
5   2  20  13
6   3  32  29
7   3  29  24
8   3  25  18
9   4   3   0
10  4   5   0
11  4   7   0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.