Iterating with conditions over Distinct Values in a Column

Viewed 15

I have a dataset that looks something like this:

category value ID
A 1 x
A 0.5 y
A 0.33 y
B 0.5 z
B 0.33 z
C 5 w
C 0.33 w

For each category, I want to grab all the instances that have a value of <= 0.5. I want to have a count of those instances for each category.

My ideal end goal would be to have a dataframe or list with the counts for each of these categories.

Thanks so much for your help.

EDIT:

To get more complex, let's say I want the count for each category where value is <=0.5 but only count each ID once.

Whereas before the values would be: cat A -> 2, cat B -> 2, cat C -> 1

Now ideal values would be: Cat A -> 1, cat B -> 1, cat C -> 1

1 Answers

You can use groupby.sum on the boolean Series of the comparison of value to 0.5:

out = df['value'].le(0.5).groupby(df['category']).sum()

Alternatively, use boolean indexing and value_counts:

df.loc[df['value'].le(0.5), 'category'].value_counts()

output:

category
A    2
B    2
C    1
Name: value, dtype: int64
Related