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.

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1, numeric_only=True)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

sum docs

Answer from EdChum 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 - Sum rows based on columns inside pandas dataframe - Stack Overflow
I am quite new to pandas, but I use python at a good level. I have a pandas dataframe which is organized as follows idrun idbasin time q -192540 1 0 0 -192540 1 ... More on stackoverflow.com
🌐 stackoverflow.com
October 1, 2021
Pandas sum row values based on condition

Try np.where

More on reddit.com
🌐 r/learnpython
13
1
July 23, 2021
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
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.sum.html
pandas.DataFrame.sum — pandas 3.0.6 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...
🌐
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.
🌐
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 - You can use the following syntax to sum the values of a column in a pandas DataFrame based on a condition:
🌐
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
🌐
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 ‘A’, ‘B’, and ‘E’ for the assists column is 27. Related: The Difference Between loc vs. iloc in Pandas · The following tutorials explain how to perform other common operations in pandas: How to Perform a SUMIF Function in Pandas How to Perform a GroupBy Sum in Pandas How to Sum Columns Based on a Condition in Pandas
🌐
Medium
medium.com › @amit25173 › understanding-pandas-dataframe-sum-a23521d6937b
Understanding pandas.DataFrame.sum() | by Amit Yadav | Medium
March 6, 2025 - You might be thinking, What if the entire column or row is NaN? Well, if you don’t want pandas to consider NaNs in the sum, use the skipna=True parameter (which is the default). But, if all the values are NaN, pandas will return 0 if skipna=True and there are no other valid values. ... When skipna=False, if there are NaN values present, pandas will return NaN for the sum. ... Of course! You can sum specific columns by simply selecting them. Here’s how: # Sum only column 'A' print(df['A'].sum()) # Or sum multiple columns print(df[['A', 'B']].sum())
🌐
datagy
datagy.io › home › pandas tutorials › data analysis in pandas › pandas sum: add dataframe columns and rows
Pandas Sum: Add Dataframe Columns and Rows • datagy
December 15, 2022 - Say we only wanted to add two columns together row-wise, rather than all of them, we can simply add the columns directly. The benefit of this approach is that we can assign a new column that stores these values. ... # Add two columns in a Pandas dataframe df['Jan_Feb_Sum'] = df['January_Sales'] + df['February_Sales'] print(df.head()) # Returns: # Name January_Sales February_Sales March_Sales Jan_Feb_Sum # 0 Nik 90 95 100 185 # 1 Kate 95 95 95 190 # 2 Kevin 75 75 50 150 # 3 Evan 93 65 75 158 # 4 Jane 60 50 90 110
🌐
Reddit
reddit.com › r/learnpython › pandas sum row values based on condition
r/learnpython on Reddit: Pandas sum row values based on condition
July 23, 2021 -

Hi friends - I am sure this is very simple but I have googled my heart out and can't figure out how to do this. I am trying to append a new column to a pandas dataframe which sums all values in existing columns only if they are even.

odd_lst = [1, 3, 5, 7, 9]
even_lst = [0, 2, 4, 6, 8]

df = pd.DataFrame()

df['Odd'] = odd_lst
df['Even'] = even_lst

df['Odd Sum'] = df.apply(some lambda function or something which only executes if values are odd, axis = 1)

Am I supposed to use lambda here? I don't know why I am struggling so much with this. I want to go row by row and only sum the values if they are odd and append this as a new column on the dataframe.

🌐
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
🌐
thisPointer
thispointer.com › home › dataframe › pandas: sum rows in dataframe ( all or certain rows)
Pandas: Sum rows in Dataframe ( all or certain rows) - thisPointer
April 30, 2023 - In this article we will discuss how to sum up rows in a dataframe and add the values as a new row in the same dataframe. ... import pandas as pd import numpy as np # List of Tuples employees_salary = [('Jack', 2000, 2010, 2050, 2134, 2111), ('Riti', 3000, 3022, 3456, 3111, 2109), ('Aadi', np.NaN, 2334, 2077, 2134, 3122), ('Mohit', 3012, 3050, 2010, 2122, 1111), ('Veena', 2023, 2232, 3050, 2112, 1099), ('Shaun', 2123, 2510, np.NaN, 3134, 2122), ('Mark', 4000, 2000, 2050, 2122, 2111)] # Create a DataFrame object from list of tuples df = pd.DataFrame(employees_salary, columns=['Name', 'Jan', 'Feb', 'March', 'April', 'May']) # Set column Name as the index of dataframe df.set_index('Name', inplace=True) print(df)
🌐
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 ...
🌐
Bobby Hadz
bobbyhadz.com › blog › pandas-sum-values-in-column-with-condition
Pandas: Sum the values in a Column that match a Condition | bobbyhadz
You can use boolean indexing to sum the values in a column in a Pandas DataFrame that match a condition. Once you select the matching values, call the DataFrame.sum() method.
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › python-pandas-dataframe-sum
Pandas dataframe.sum() - GeeksforGeeks
March 18, 2025 - DataFrame.sum() function in Pandas allows users to compute the sum of values along a specified axis. It can be used to sum values along either the index (rows) or columns, while also providing flexibility in handling missing (NaN) values.
🌐
Arab Psychology
scales.arabpsychology.com › psychological scales › how to sum columns based on a condition
How To Sum Columns Based On A Condition
November 15, 2023 - The following code shows how to find the sum of the points for the rows where team is equal to ‘A’ or ‘B’: df.loc[df['team'].isin(['A', 'B']), 'points'].sum() 41 · You can find more pandas tutorials on . ... stats writer (2023). How to Sum Columns 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...