• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Sum Columns Dynamically with pandas in Python

Sum Columns Dynamically with pandas in Python

August 27, 2022 Leave a Comment

To sum columns dynamically, you can create a list containing the columns you want and use the sum() function, passing “axis=1”.

import pandas as pd

df = pd.read_csv("some_data.csv")

cols_to_sum = ["col1","col2"]

df["Total"] = df[cols_to_sum].sum(axis=1)

When working with collections of data, the ability to aggregate different pieces of data in different ways easily is valuable.

One such case is if you have a dataset and want to create new columns from the sum of other columns.

You can sum columns dynamically with pandas easily.

First, you build a list containing the column names you want to sum and then you can use the sum() function. By default, sum() sums the rows, and so you need to pass “axis=1” to sum over the columns.

Below is a simple example showing you how to sum varying columns in Python with pandas.

import pandas as pd

df = pd.read_csv("some_data.csv")

cols_to_sum = ["col1","col2"]

df["Total"] = df[cols_to_sum].sum(axis=1)

This is useful if you have a loop and want to create different sums based on differing columns depending on certain conditions.

import pandas as pd

df = pd.read_csv("some_data.csv")

for x in range(0,10):
    cols_to_sum = ["col" + str(x),"col2" + str(x + 1)]
    df["Total" + str(x)] = df[cols_to_sum].sum(axis=1)

Other Functions to Use to Aggregate Columns Dynamically with pandas

You can use the same structure from above to aggregate your data with different calculations.

For example, you could take the max over different columns with the pandas DataFrame max() function in the following way.

import pandas as pd

df = pd.read_csv("some_data.csv")

cols = ["col1","col2"]

df["Max"] = df[cols].max(axis=1)

If you wanted to get the mean of multiple columns in pandas, you could use the pandas DataFrame mean() function as shown below.

import pandas as pd

df = pd.read_csv("some_data.csv")

cols = ["col1","col2"]

df["Mean"] = df[cols].mean(axis=1)

There are many great functions which pandas offers us and you can explore them in the documentation here.

Hopefully this article has been useful for you to learn how to sum columns dynamically with pandas in Python.

Other Articles You'll Also Like:

  • 1.  Check if Variable is None in Python
  • 2.  Python power function – Exponentiate Numbers with math.pow()
  • 3.  Get Year from Date in Python
  • 4.  Python gethostbyname() Function – Get IPv4 Address from Name
  • 5.  How to Hide Turtle in Python with hideturtle() Function
  • 6.  Check if String Contains Only Certain Characters in Python
  • 7.  Using Python to Repeat Characters in String
  • 8.  pandas groupby size – Get Number of Elements after Grouping DataFrame
  • 9.  Get Public IP Address Using Python
  • 10.  Find Magnitude of Complex Number in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy