Home > Enterprise >  Apply different mathematical function in table in Python
Apply different mathematical function in table in Python

Time:06-11

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

CodePudding user response:

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

CodePudding user response:

IIUC, you can try DataFrame.apply on rows with operator

import operator

operators = [operator.add, operator.sub, operator.mul, operator.truediv]

df['C'] = df.apply(lambda row: operators[row.name](*row), axis=1)
print(df)

   A  B     C
0  5  1   6.0
1  6  2   4.0
2  7  3  21.0
3  8  4   2.0
  • Related