Suppose I have a column 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?
This question is related to
python
pandas
dataframe
data-analysis
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())
Source: Stackoverflow.com