StackOverCats
StackOverCats

Reputation: 15

count the frequency that a value occurs in the end of a dataframe column

I have a dataset

|category|
cat a
cat a
cat b
cat b
cat a
cat b
cat a
cat a
cat a
cat a

I'd like to be able to return the total 4 for cat a that occurs at the end of the dataframe in other words if cat b happens then the count starts over once another cat a is found

Upvotes: 1

Views: 45

Answers (1)

adir abargil
adir abargil

Reputation: 5745

df['category'] = np.where(df['category'] == "cat b", df['category'],np.nan)
df['category'].bfill().isna().sum()
>>>4

Upvotes: 1

Related Questions