'How to do a mathematical operation pandas dataframe

If I have three columns in pandas dataframe (CSV File), and I need to do a mathematical operation in the third column depending on the other two columns' values how can I do it? for example, if I have three columns

enter image description here

I need to change column " C " to a mathematical operation which is: C = 3*A + B So the output must be:

C = (3*2) + 4 = 10 ...........
C = (4*2) + 8 = 16

enter image description here

So, how can I do this by a python code?



Solution 1:[1]

df['C'] = df['A'] * 3 + df['B'] 

Solution 2:[2]

df = pd.DataFrame()
df["A"] = [2,4]
df["B"] = [4,8]
df["C"] = [10,16]
df["C"] = 3*df["A"] + df["B"]

Solution 3:[3]

You can use df.eval or DataFrame mathematics operator

df['C'] = df.eval('3 * A + B')

# or

df['C'] = df['A'].mul(3).add(df['B'])
print(df)

   A  B   C
0  2  4  10
1  4  8  20

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec
Solution 2 Anytokin
Solution 3 Ynjxsjmh