Home > Enterprise >  summing two columns in a dataframe
summing two columns in a dataframe

Time:08-07

My df looks as follows:

     Roll   Name    Age  Physics  English  Maths 
0     A1    Max     16     87       79      90
1     A2    Lisa    15     47       75      60
2     A3    Luna    17     83       49      95
3     A4    Ron     16     86       79      93
4     A5    Silvia  15     57       99      91

I'd like to add the columns Physics, English, and Maths and display the results in a separate column 'Grade'.

I've tried the code:

df['Physics']   df['English']   df['Maths']

But it just concatenates. I am not taught about the lambda function yet. How do I go about this?

CodePudding user response:

df['Grade'] = df['Physics']   df['English']   df['Maths']

it concatenates maybe your data is in **String** just convert into float or integer. Check Data Types First by using df.dtypes

CodePudding user response:

Try:

df["total"] = df[["Physics", "English", "Maths"]].sum(axis=1)
df

CodePudding user response:

Check Below code, Its is possible you columns are in string format, belwo will solve that:

import pandas as pd

df = pd.DataFrame({"Physics":['1','2','3'],"English":['1','2','3'],"Maths":['1','2','3']})

df['Total'] = df['Physics'].astype('int')  df['English'].astype('int')  df['Maths'].astype('int')

df

Output:

enter image description here

  • Related