Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading