The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8
Answer from Alex Riley on Stack Overflow
Top answer
1 of 3
182

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8
2 of 3
11

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
Discussions

python - Pandas: sum DataFrame rows for given columns - Stack Overflow
You can just sum and set axis=1 to sum the rows, which will ignore non-numeric columns; from pandas 2.0+ you also need to specify numeric_only=True. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Pandas - how to get sum of column for specific/certain rows
I think this is what groupby is for: df["driver mileage"] = df.groupby["driver"]. sum() Or something like that. And then get the driver with df["driver mileage"].idxmax() I think. More on reddit.com
๐ŸŒ r/learnpython
11
1
August 10, 2021
Summing Rows based on column lookup
Sounds like what you after is a combination of sum, index and match. You can try https://www.youtube.com/results?search_query=sum%2C+index+and+match I understand your wanting to you pick option from column D you get the sum of the values in G:M. I my recreateion i did it as both a drop down option (P2) using data validation and put theformula in Q2. =SUM(INDEX(G:M,MATCH(P2,D:D,0),0)) OR you can have all of them like in column S and formula in T2 =SUM(INDEX(G:M,MATCH(S2,D:D,0),0)) The yellow highlighted are to show it is giveing the correct result when you do a normal sum of each row values. More on reddit.com
๐ŸŒ r/excel
4
3
July 20, 2023
Sum across multiple columns by column name

There are a few concepts here:

  • If you're doing rowwise operations you're looking for the rowwise() function

  • With rowwise data frames you use c_across() inside mutate() to select the columns you're operating on

  • And if you're trying to use a character vector like firstSum to select columns you wrap it in the select helper any_of()

  • Afterwards you need to "ungroup" the data frame so that it no longer tries to do operations rowwise

library(tidyverse)

df <- data.frame(a = 1:2, b = 2:3, c = 3:4, d = 4:5)

firstSum <- c("a", "b")
secondSum <- c("c", "d")

df %>%
  rowwise() %>%
  mutate(first = sum(c_across(any_of(firstSum))),
         second = sum(c_across(any_of(secondSum)))) %>%
  ungroup()
#> # A tibble: 2 x 6
#>       a     b     c     d first second
#>   <int> <int> <int> <int> <int>  <int>
#> 1     1     2     3     4     3      7
#> 2     2     3     4     5     5      9

Hope this helps! If you have any questions let me know

More on reddit.com
๐ŸŒ r/Rlanguage
14
4
June 28, 2020
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas sum dataframe rows with examples
Pandas Sum DataFrame Rows With Examples - Spark By {Examples}
December 3, 2024 - To sum all Pandas DataFrame rows or given selected rows use the sum() function. The Pandas DataFrame.sum() function returns the sum of the values for the
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ pandas โ€บ ref_df_sum.asp
Pandas DataFrame sum() Method
import pandas as pd data = [[10, 18, 11], [13, 15, 8], [9, 20, 3]] df = pd.DataFrame(data) print(df.sum()) Try it Yourself ยป ยท The sum() method adds all values in each column and returns the sum for each column.
๐ŸŒ
Medium
medium.com โ€บ @amit25173 โ€บ understanding-pandas-dataframe-sum-a23521d6937b
Understanding pandas.DataFrame.sum() | by Amit Yadav | Medium
March 6, 2025 - If you want to sum the rows, set axis=1. skipna: By default, this is set to True. It means that if there are any missing (NaN) values in your DataFrame, pandas will ignore them when performing the sum.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-sum-values-of-pandas-dataframe-by-rows
How to sum values of Pandas dataframe by rows? - GeeksforGeeks
March 26, 2021 - Summing all the rows of a Dataframe using the sum function and setting the axis value to 1 for summing up the row values and displaying the result as output. ... # importing pandas module as pd import pandas as pd # creating a dataframe using ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Sum Rows By Specific Columns in a Pandas ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Find elsewhere
๐ŸŒ
Statology
statology.org โ€บ home โ€บ how to sum specific rows in pandas (with examples)
How to Sum Specific Rows in Pandas (With Examples)
September 27, 2022 - The sum of rows with index values 0, 1, and 4 for the assists column is 27. Also note that you can sum a specific range of rows by using the following syntax:
๐ŸŒ
Easy Tweaks
easytweaks.com โ€บ python-pandas-sum-columns-dataframe
How to sum specific multiple rows in a Pandas DataFrame?
August 26, 2021 - Master meetings, chats, channels and online collaboration ยท Go beyond the basics in Word, Excel, PowerPoint and Outlook
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-pandas-dataframe-sum
Pandas dataframe.sum() - GeeksforGeeks
March 18, 2025 - Explanation: Instead of adding up values in columns, this example sums up values in each row. First, it selects only numeric columns to avoid errors. Missing values are ignored during the summation. The min_count parameter ensures that the sum operation is performed only if at least a certain number of non-NaN values are present. Otherwise, the result will be NaN. ... import pandas as pd import numpy as np data = {'A': [1, np.nan, 3, np.nan], 'B': [4, np.nan, np.nan, np.nan], 'C': [7, 8, 9, np.nan]} df = pd.DataFrame(data) # Sum columns but require at least 2 valid values df_sum_min_count = df.sum(axis=0, min_count=2) print("\nSum with min_count=2:") print(df_sum_min_count)
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas sum dataframe columns with examples
Pandas Sum DataFrame Columns With Examples - Spark By {Examples}
November 4, 2024 - To sum Pandas DataFrame columns (given selected multiple columns) using either sum(), iloc[], eval(), and loc[] functions. Among these Pandas
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ python-group-and-calculate-the-sum-of-column-values-of-a-pandas-dataframe
Python โ€“ Group and calculate the sum of column values of a Pandas DataFrame
March 26, 2026 - import pandas as pd # Create DataFrame dataFrame = pd.DataFrame({ "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"], "Date_of_Purchase": [ pd.Timestamp("2021-06-10"), pd.Timestamp("2021-07-11"), pd.Timestamp("2021-06-25"), pd.Timestamp("2021-06-29"), pd.Timestamp("2021-03-20"), pd.Timestamp("2021-01-22"), pd.Timestamp("2021-01-06"), pd.Timestamp("2021-01-04"), pd.Timestamp("2021-05-09") ], "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] }) # Group by month and calculate sum monthly_sum = dataFrame.groupby(pd.Grouper(key='Date_of_P
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ third party โ€บ pandas โ€บ dataframe โ€บ sum()
Python Pandas DataFrame sum() - Sum Column Values
December 25, 2024 - The sum() function in Python's Pandas library is a crucial tool for performing aggregation operations on DataFrame columns. This method sums up the values in each column by default, or along the rows if specified, facilitating quick statistical ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
PYTHON PANDAS TUTORIAL #13 - SUMMING COLUMNS OR ROWS VALUES. - YouTube
In this lesson we will learn how to SUM COLUMNS OR ROWS VALUES in pandas. Make sure you watch and practice my lessons at the same time.Chapters: 1:45 - H...
Published: May 26, 2023
๐ŸŒ
Saturn Cloud
saturncloud.io โ€บ blog โ€บ how-to-sum-values-of-a-row-of-a-pandas-dataframe-efficiently
Efficient Techniques for Summing Row Values in Pandas Dataframes | Saturn Cloud Blog
May 1, 2026 - The most efficient way to sum values of a row of a pandas dataframe is to use the sum() method with the axis parameter set to 1. The axis parameter specifies whether to sum the rows (0) or the columns (1).
๐ŸŒ
Statology
statology.org โ€บ home โ€บ pandas: how to sum columns based on a condition
Pandas: How to Sum Columns Based on a Condition
January 18, 2021 - by Zach Bobbitt Published on Published on January 18, 2021 ยท You can use the following syntax to sum the values of a column in a pandas DataFrame based on a condition:
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pandas - how to get sum of column for specific/certain rows
r/learnpython on Reddit: Pandas - how to get sum of column for specific/certain rows
August 10, 2021 -

The data is stored like so with driver & miles as two columns. I want to find the driver that has the most miles

driver                                miles
Driver A                              200
Driver B                              410
Driver A                              350

I put the data into a dataframe & sort by miles like so

df = pd.read_sql_query('SELECT * FROM "autos"', con=engine)
df = df.sort_values(by=['miles'], ascending=False)

& the output is that Driver B is first (410) but I want Driver A to be first (550 = 200 + 350). At some point I guess I need to sum all drivers individually & then sort? First idea was to slice but that would remove many drivers & next I tried the axis but have yet to get it right. When I sum drivers individually & place them in a new column the number of rows didn't match & I got an error? All feedback is welcome...

๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.DataFrame.sum.html
pandas.DataFrame.sum โ€” pandas 3.0.5 documentation
The behavior of DataFrame.sum with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar To retain the old behavior, pass axis=0 (or do not pass axis). Added in version 2.0.0. ... Exclude NA/null values when computing the result. ... Include only float, int, boolean columns...