sum values of multiple columsn rowwise in python

To sum values of multiple columns row-wise in Python using Pandas, you can use the sum method along with the axis parameter set to 1.

Consider the following example DataFrame:

main.py
import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'Salary': [50000, 60000, 70000],
        'Expense': [2000, 3000, 4000]}
df = pd.DataFrame(data)
199 chars
8 lines

This creates a DataFrame with four columns - Name, Age, Salary and Expense.

To sum the values of the Salary and Expense columns row-wise and add the result as a new column Total, you can use the following code:

main.py
df['Total'] = df[['Salary', 'Expense']].sum(axis=1)
52 chars
2 lines

This will create a new column Total with the sum of the Salary and Expense values row-wise.

You can modify this code to sum values of any combination of columns that you want.

main.py
df['New Total'] = df[['Age', 'Salary', 'Expense']].sum(axis=1)
63 chars
2 lines

This will create a new column New Total with the sum of the Age, Salary, and Expense columns.

related categories

gistlibby LogSnag