mathology
mathology

Reputation: 147

pandas rolling get most frequent value in window

I was wondering how one could obtain the most frequent value of in a rolling window of a time series, i.e. something like

df.rolling(window = 2).rolling.count_values().idxmax()

Since for the column of a data frame, one can use

df["value"].count_values().idxmax()

However, I only get an error message reading 'Rolling' object has no attribute 'count_values'

Upvotes: 1

Views: 1176

Answers (1)

Alexander Volkovsky
Alexander Volkovsky

Reputation: 2918

Use rolling().apply with mode method:

df.rolling(window = 3).apply(lambda x: x.mode()[0])

x will be a pd.Series object of length equal to window. mode method will return a list of most frequent values. lambda will return the first item from the list of modes.

Upvotes: 2

Related Questions