Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing addition and subtraction operations within the columns of the same python DataFrame

I have a data Dataframe like,

data = {
  "A": [42, 38, 39,23],
  "B": [45, 30, 15,65],
  "C": [60, 50, 25,43],
  "D": [12, 70, 35,76,],
  "E": [87, 90, 45,43],
  "F": [40, 48, 55,76],
  "G": [58, 42, 85,10],
}
df = pd.DataFrame(data)

print(df)
    A   B   C   D   E   F   G
0  42  45  60  12  87  40  58
1  38  30  50  70  90  48  42
2  39  15  25  35  45  55  85
3  23  65  43  76  43  76  10

Here, I need to subtract all the values of columns C to G from column B, then add column A.

Like

df['C']=df['C']-df['B']+df['A']
df['D']=df['D']-df['B']+df['A']
df['E']=df['E']-df['B']+df['A']

How it is possible in simple/single commands?

like image 266
Aristocrat Avatar asked Oct 15 '25 20:10

Aristocrat


1 Answers

You can use a single eval with a multiline expression:

df = df.eval('''C=C-B+A
D=D-B+A
E=E-B+A
''')

Or, for this particular operation, since all are +A-B:

df[['C', 'D', 'E']] = df[['C', 'D', 'E']].add(df['A'].sub(df['B']), axis=0)

Output:

    A   B   C   D   E   F   G
0  42  45  57   9  84  40  58
1  38  30  58  78  98  48  42
2  39  15  49  59  69  55  85
3  23  65   1  34   1  76  10
like image 197
mozway Avatar answered Oct 18 '25 10:10

mozway