Sum of two or more columns of pandas dataframe in python is carried out using + operator. Lets see how to
- Sum the two columns of a pandas dataframe in python
- Sum more than two columns of a pandas dataframe in python
With an example of each
First let’s create a dataframe
import pandas as pd import numpy as np #Create a DataFrame df1 = { 'Name':['George','Andrea','micheal','maggie','Ravi','Xien','Jalpa'], 'Mathematics1_score':[62,47,55,74,32,77,86], 'Mathematics2_score':[45,78,44,89,66,49,72], 'Science_score':[56,52,45,88,33,90,47]} df1 = pd.DataFrame(df1,columns=['Name','Mathematics1_score','Mathematics2_score','Science_score']) print(df1)
df1 will be
Sum of two columns of a pandas dataframe in python
Sum of two mathematics score is computed using simple + operator and stored in the new column namely Mathematics_score as shown below
df1['Mathematics_score']=df1['Mathematics1_score'] + df1['Mathematics2_score'] print(df1)
so resultant dataframe will be (Mathematics1_score + Mathematics2_score)
Sum of more than two columns of a pandas dataframe in python
Sum of all the score is computed using simple + operator and stored in the new column namely total_score as shown below
df1['total_score']=df1['Mathematics1_score'] + df1['Mathematics2_score']+ df1['Science_score'] print(df1)
so resultant dataframe will be