You should use sum:

Total = df['MyColumn'].sum()
print(Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index=['MyColumn'])
print(df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print(df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print(df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print(df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.

Answer from jezrael on Stack Overflow
Top answer
1 of 6
412

You should use sum:

Total = df['MyColumn'].sum()
print(Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index=['MyColumn'])
print(df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print(df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print(df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print(df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.

2 of 6
42

Another option you can go with here:

df.loc["Total", "MyColumn"] = df.MyColumn.sum()

#         X  MyColumn      Y       Z
#0        A     84.0    13.0    69.0
#1        B     76.0    77.0   127.0
#2        C     28.0    69.0    16.0
#3        D     28.0    28.0    31.0
#4        E     19.0    20.0    85.0
#5        F     84.0   193.0    70.0
#Total  NaN    319.0     NaN     NaN

You can also use append() method:

df.append(pd.DataFrame(df.MyColumn.sum(), index = ["Total"], columns=["MyColumn"]))


Update:

In case you need to append sum for all numeric columns, you can do one of the followings:

Use append to do this in a functional manner (doesn't change the original data frame):

# select numeric columns and calculate the sums
sums = df.select_dtypes(pd.np.number).sum().rename('total')

# append sums to the data frame
df.append(sums)
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     319.0  400.0  398.0

Use loc to mutate data frame in place:

df.loc['total'] = df.select_dtypes(pd.np.number).sum()
df
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     638.0  800.0  796.0
Discussions

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
Pandas: How to sum list of columns by row?
The syntax should be correct, and this warning would rather suggest that df is already a copy, perhaps from some other operation. Are you able to provide the full history of the dataframe object? More on reddit.com
🌐 r/learnpython
6
5
January 28, 2018
python - How do I sum values in a column that match a given condition using pandas? - Stack Overflow
Suppose I have a dataframe like so: a b 1 5 1 7 2 3 1 3 2 5 I want to sum up the values for b where a = 1, for example. This would give me 5 + 7 + 3 = 15. How do I do this in pandas? More on stackoverflow.com
🌐 stackoverflow.com
python - Pandas: sum up multiple columns into one column without last column - Stack Overflow
If I have a dataframe similar to this one Apples Bananas Grapes Kiwis 2 3 nan 1 1 3 7 nan nan nan 2 3 I would like to add a column... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-pandas-dataframe-sum
Pandas dataframe.sum() - GeeksforGeeks
July 11, 2025 - 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)
🌐
W3Schools
w3schools.com › python › pandas › ref_df_sum.asp
Pandas DataFrame sum() Method
By specifying the column axis (axis='columns'), the sum() method searches column-wise and returns the sum of each row.
🌐
Medium
medium.com › @amit25173 › understanding-pandas-dataframe-sum-a23521d6937b
Understanding pandas.DataFrame.sum() | by Amit Yadav | Medium
March 6, 2025 - By default, it's set to 0, meaning it will sum the columns. 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 ...
🌐
Programiz
programiz.com › python-programming › pandas › methods › sum
Pandas sum() (With Examples)
import pandas as pd # create a DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) # calculate the sum of each column column_sum = df.sum() print(column_sum) ''' Output A 6 B 15 dtype: int64 '''
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › pandas-groupby-and-sum
Pandas Groupby and Sum - GeeksforGeeks
July 23, 2025 - Pandas dataframe.sum() function returns the sum of the values for the requested axis. If the input is the index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of ...
🌐
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...

🌐
Reddit
reddit.com › r/learnpython › pandas: how to sum list of columns by row?
r/learnpython on Reddit: Pandas: How to sum list of columns by row?
January 28, 2018 -

I am trying to sum a list of columns by row.

First I tried:

col_list = ['A', 'B', 'C']
df['total'] = df[col_list].sum(axis = 1)

But this returns the dreaded SettingWithCopyWarning. I have tried reading through the documentation located here, as well as some blog posts, but can't get very far. I am confused on how to create the new column. This is my working but incomplete code:

df.loc[ : , col_list].sum(axis = 1)

How do I assign those values to a new column without the SettingWithCopy warning?

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())
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas get total / sum of columns
Pandas Get Total / Sum of Columns - Spark By {Examples}
October 14, 2024 - To get the total or sum of a column use sum() method, and to add the result of the sum as a row to the DataFrame use loc[], at[], append() and
🌐
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
🌐
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 ...
🌐
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 - Similar to the example above, we can make use of the .sum method. By default, Pandas will apply an axis=0 argument, which will add up values index-wise. If we can change this to axis=1, values will be added column-wise.
🌐
Pandas
pandas.pydata.org › docs › getting_started › intro_tutorials › 06_calculate_statistics.html
How to calculate summary statistics — pandas 3.0.6 documentation
Calculating a given statistic (e.g. mean age) for each category in a column (e.g. male/female in the Sex column) is a common pattern. The groupby method is used to support this type of operations. This fits in the more general split-apply-combine pattern: ... The apply and combine steps are typically done together in pandas.
🌐
IncludeHelp
includehelp.com › python › how-to-sum-values-in-a-column-that-matches-a-given-condition-using-pandas.aspx
How to sum values in a column that matches a given condition using Pandas?
# Importing pandas package import pandas as pd # Creating a dictionary d= { 'Col_1':[1,5,10,1,5,10,1,5,10,1,5,10], 'Col_2':[10,20,30,40,50,60,70,80,90,100,110,120] } # Creating a DataFrame df = pd.DataFrame(d) # Display original DataFrame print("Original DataFrame:\n",df,"\n") # Performing our operation result = df.loc[df['Col_1'] == 1, 'Col_2'].sum() # Display result print("Result,\n",result)
🌐
Python.org
discuss.python.org › python help
Sum of columns pandas - Python Help - Discussions on Python.org
October 9, 2022 - Hello I’m new to python some 6 weeks in, and working on my project. I have a trouble creating a new column that would sum two existing ones, that I’ve created form Pivot Tables. The bale look like this: size Timely_Response No Yes Company WELLS FARGO & COMPANY 3244.0 67675.0 EQUIFAX, INC.