【问题标题】:Select top 5 from each month using value counts on a DateTimeIndex with Pandas使用 Pandas 的 DateTimeIndex 上的值计数从每个月中选择前 5 个
【发布时间】:2020-08-11 23:51:52
【问题描述】:

我有一个pandas DataFrame 和一个DatetimeIndex。我想resample by month 并从特定的DataFrame 中为每个month 获取top 5 column 但是使用nlargest(5) 给了我整个DataFrame 的前5 名而不是按月:

这是我的代码的snippet

df.resample("M").productID.value_counts().nlargest(5)

这给了我整个 DataFrame 的前 5 名,我需要每个月都有前 5 名。

【问题讨论】:

    标签: python pandas dataframe datetime pandas-groupby


    【解决方案1】:

    因为value_counts默认排序是可能的,所以使用head代替nlargest

    df.resample("M").productID.apply(lambda x: x.value_counts().head(5))
    

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2021-04-07
      • 2020-09-12
      • 1970-01-01
      • 2020-07-18
      相关资源
      最近更新 更多