user5826447
user5826447

Reputation: 367

python pandas df: adding to one column depending on the value in that row in another column

I have a df that looks like:

    a   b   c   d
0   0   0   0   0
1   0   0   0   0
2   1   292 0   0
3   0   500 1   406
4   1   335 0   0

I would like to find the sum of column b where a=1 for that row. So in my example I would want rows 2 and 4 added (just column b), but not row 3. If it makes any difference, there are only 0s and 1s. Thanks for any help!

Upvotes: 1

Views: 83

Answers (1)

Alexander
Alexander

Reputation: 109526

You need to use .loc

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

You can review the docs here for indexing and selecting data.

Upvotes: 1

Related Questions