How do I sum values in a column that match a given condition using pandas?
Asked Answered
H

3

99

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?

Hola answered 30/1, 2015 at 12:48 Comment(0)
T
178

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
Trilinear answered 30/1, 2015 at 12:53 Comment(0)
M
7

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())
Motivation answered 11/5, 2019 at 11:20 Comment(0)
P
5

If you want to assign the summations back into the frame as a column, then you can use groupby.transform to make the sums have the same index as the original frame.

# group by values of df.a
df['b_sum_by_a'] = df.groupby('a')['b'].transform('sum')

# group by whether df.a is 1 or not
df['b_sum_by_a'] = df.groupby(df['a']==1)['b'].transform('sum')

res

Propagandism answered 15/2, 2023 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.