mohamed habib
mohamed habib

Reputation: 53

contingence two columns pandas python3

I'm looking for if there is a direct way to count the sum of the elements of b when a=1.

a

   a  b     c   d
0  4  2   NaN   7
1  1  2  45.0  74
2  1  4   7.0   8

So this case it must be 6. I can do it easily with my own code but I have a large data set, so I want to know the best way to do it . Thank you.

import pandas as pd
a=pd.DataFrame([[4,2,None,7],[1,2,45,74],[1,4,7,8]],columns=(['a','b','c','d'])) 

Upvotes: 0

Views: 32

Answers (1)

Jon Deaton
Jon Deaton

Reputation: 4379

Does

a.loc[a.a == 1].b.sum()

work?

Upvotes: 1

Related Questions