Home > Back-end >  How to do a mathematical operation pandas dataframe
How to do a mathematical operation pandas dataframe

Time:05-09

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  • Related