How can I select the most frequent category / text over a rolling interval?

Viewed 31

I have a data frame with a column that shows a certain category with a letter:

                    date  gradient category
0   2022-04-15 10:00:00  0.135626     S
1   2022-04-15 11:00:00  0.017990     A
2   2022-04-15 12:00:00  0.026333   S-A
3   2022-04-15 13:00:00  0.028347   S-A
4   2022-04-15 14:00:00  0.147611     S
..                  ...       ...   ...
411 2022-05-02 13:00:00  0.006906     D
412 2022-05-02 14:00:00  0.003823     D
413 2022-05-02 15:00:00  0.145872     S
414 2022-05-02 16:00:00  0.186694     S
415 2022-05-02 17:00:00  0.955833   NaN 

The variance of the categories changing is to frequent. So I would like to make a function that gives me the most presented category over a rolling interval in a new column. So for example:

(S, A, A, A, D, S-A, A)

Will result in 'A', because that's the most frequent one.

1 Answers

You can count the appearances with the Counter object and then take the most frequent appearance:

from collections import Counter

column = ("S", "A", "A", "A", "D", "S-A", "A")

counter = Counter(column)
# returns a sorted list of elements and number of appearances
frequencies = counter.most_common()

# grab the first (most common) element and its frequency.
most_frequent_element, frequency = fequencies[0]

print(most_frequent_element, frequency)

output:

A 4
Related