close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I sum values in a column that match a given condition using pandas in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

  1. How do I sum values in a column that match a given condition using pandas?

    You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df.

  2. sum values in a column that match a given condition using pandas

    You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df.

Method 1

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())

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read