简体   繁体   中英

summing two columns in a dataframe

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?

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

Try:

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

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM