Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

pandas sum dataframe columns

# Below are quick example
# Using DataFrame.sum() to Sum of each row
df2 = df.sum(axis=1)

# Sum the rows of DataFrame
df['Sum'] = df.sum(axis=1)

# Just a few columns to sum
df['Sum'] = df['mathantics'] + df['science'] + df['english']

# Remove english column
col_list= list(df)
col_list.remove('english')

# sum specific columns
col_list= list(df)
col_list.remove('english')
df['Sum'] = df[col_list].sum(axis=1)

# Select 1 to 3 columns to sum
df['Sum']=df.iloc[:,1:3].sum(axis=1)

# Select 1 and 2 columns to sum Using DataFrame.iloc[] 
df['Sum']=df.iloc[:,[1,2]].sum(axis=1)

# Using DataFrame.iloc[] to select 2 and 3 columns to sum
df['Sum']=df.iloc[:,[2,3]].sum(axis=1)

# Sum columns Fee and Discount for row from r2 to r3
df['Sum'] = df.loc['r2':'r4',['mathantics','science']].sum(axis = 1)

# Using DataFrame.eval() function to sum of rows
df2 = df.eval('Sum = mathantics + english')

# Using DataFrame.loc[] and eval function to sum specific rows
df2 = df.loc['r2':'r4'].eval('Sum = mathantics + science')
Source by sparkbyexamples.com #
 
PREVIOUS NEXT
Tagged: #pandas #sum #dataframe #columns
ADD COMMENT
Topic
Name
5+3 =