Kiann
Kiann

Reputation: 571

python count number of times pandas series value goes above value X

I see there are various python/pandas argument to count number of occurrences.

However, is there a way to count the number of times, when the series values goes above $X? It shouldn't double-count for the time when the series value is above $X. It should count only when it goes above it.

For example, in the data series below, I would expect the count = 2, and not 4; given X = $200.

list_a = [100, 150, 210, 185, 166, 205, 230, 222, 195, 190, 160]
pd.DataFrame(list_a, columns = ['mtm_level'])

Upvotes: 1

Views: 359

Answers (1)

ALollz
ALollz

Reputation: 59549

Check with cumsum of a Boolean Series + where + nunique. Here "above" is not inclusive of X

X = 200
df['mtm_level'].le(X).cumsum().where(df['mtm_level'].gt(X)).nunique()
#2

X = 1000
df['mtm_level'].le(X).cumsum().where(df['mtm_level'].gt(X)).nunique()
#0

Upvotes: 3

Related Questions