首页 > 解决方案 > 熊猫滚动在窗口中获得最频繁的值

问题描述

我想知道如何在时间序列的滚动窗口中获得最频繁的值,即类似

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

由于对于数据框的列,可以使用

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

但是,我只收到一条错误消息阅读 'Rolling' object has no attribute 'count_values'

标签: pythonpandas

解决方案


使用rolling().applywith mode方法:

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

x将是一个pd.Series长度等于窗口的对象。mode方法将返回最常见值的列表。lambda将返回模式列表中的第一项。


推荐阅读