Apply different mathematical function in table in Python

Issue

I have two columns – Column A and Column B and it has some values like below:-

enter image description here

Now, I want to apply normal arithmetic function for each row and add result in next column. But Different arithmetic operator should be apply on each row. Like

A+B for first row

A-B for second row

A*B for third row

A/B for fourth row

and so on till nth record of the row with same repetitive mathematical function.

Can someone please help me with this code in Python.
python-3.x
pandas

Solution

We can use:

  • row.name to access the index when using apply on a row
  • can use a dictionary to map indexes to a operations

Code

import operator as _operator

# Data
d = {"A":[5, 6, 7, 8, 9, 10, 11],
    "B": [1, 2, 3, 4, 5, 6, 7]}

df = pd.DataFrame(d)

print(df)

# Mapping from index to mathematical operation
operator_map = {
    0: _operator.add,
    1: _operator.sub,
    2: _operator.mul,
    3: _operator.truediv,
}

# use row.name % 4 to have operators have a cycle of 4
df['new'] = df.apply(lambda row: operator_map[row.name % 4](*row), axis = 1)

Output

Initial df

    A   B
0   5   1
1   6   2
2   7   3
3   8   4
4   9   5
5   10  6
6   11  7

New df

    A   B   new
0   5   1   6.0
1   6   2   4.0
2   7   3   21.0
3   8   4   2.0
4   9   5   14.0
5   10  6   4.0
6   11  7   77.0

Answered By – DarrylG

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published