Pandas: Sum up multiple columns into one column without last column

Given a DataFrame, we need to create a new column in which contains sum of values of all the columns row wise.
Submitted by Pranit Sharma, on July 21, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Suppose, we have a dataframe that contains multiple columns of bowlers' names having their values containing runs on their six continue balls, we need to calculate the row-wise sum of all the balls except for the last column. For this purpose, we will use pandas.DataFrame.iloc property for slicing so that we can select from the first column to the second last column. Then we will use sum() method to calculate the sum and finally we will store all these values in a new column of the dataframe.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python code to create a new column in which contains sum of values of all the columns row-wise

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'Shami':[0,0,2,4,4,1],
    'Bumrah':[1,1,1,0,0,2],
    'Ishant':[2,0,0,0,4,4],
    'Bhuvneshwar':[1,1,1,0,0,2]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display DataFrame
print("Created DataFrame\n",df,"\n")

# Creating new column n which sum of all columns 
# will be assigned except last column
df['Ball wise total runs']= df.iloc[:, -4:-1].sum(axis=1)

# Display modified dataframe
print("Modified DataFrame:\n",df)

Output:

Example: Sum up multiple columns into one column without last column

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.