How to do a calculation based off a T/F condition in a Pandas DataFrame

So I am really not sure how I should go about this. I am working with pandas in python. I have a csv file I converted into a data frame called df. I have this column:

Is_High_School
FALSE
FALSE
FALSE
TRUE
FALSE
...

And I have another column:

Student_Count
454
343
213
223
676
...

I want to calculate the mean and stdev of the student count, but only where Is_High_School is FALSE.

May I get some direction with how to approach this? I have tried the df.where(), and it isn't working for me because I get NaN, and I don't know how to propagate that so that I can calculate in another column only where that condition is met. Thanks, I really appreciate it.

edit:

I created a smaller dataframe called hs. Here it is:

dataframe:   Is_High_School  Student_Count_Total
0             False                  415
1             False                  241
2             False                  346
3             False                   91
4             False                  248
..              ...                  ...
655           False                  509
656           False                  507
657            True                  341
658            True                 1086
659            True                 1308

Answers 1

  • Just filter your dataframe according to the condition is required then calculate it.

    filtered_df=df.loc[df['Is_High_School'] ==False]
    
    mean_val=filtered_df['Student_Count'].mean()
    
    std_dev=filtered_df['Student_Count'].std()
    
    

Related Articles