【问题标题】:Resample with categories in pandas, keep non-numerical columns使用 pandas 中的类别重新采样,保留非数字列
【发布时间】:2019-09-23 21:30:36
【问题描述】:

我有 3 种类型的变量 x 的每小时数据,Category 列,ds 设置为索引。

> df

ds                   Category   X
2010-01-01 01:00:00     A       32
2010-01-01 01:00:00     B       13
2010-01-01 01:00:00     C       09
2010-01-01 02:00:00     A       12
2010-01-01 02:00:00     B       62
2010-01-01 02:00:00     C       12

我想将其重新采样为 Week。但如果我使用df2 = df.resample('W').mean(),它只会删除“类别”列。

【问题讨论】:

标签: python pandas


【解决方案1】:

如果需要resampleCategory 列每周添加groupby,使用DataFrameGroupBy.resample 也是如此:

通知
正确的工作是必要的DatetimeIndex

df2 = df.groupby('Category').resample('W').mean()
print (df2)
                        X
Category ds              
A        2010-01-03  22.0
B        2010-01-03  37.5
C        2010-01-03  10.5

【讨论】:

    【解决方案2】:

    为了完成answer by jezrael,我发现将内容放回DataFrame 而不是DataFrameGroup 很有用,正如here 所解释的那样。所以,答案是:

    df2 = df.groupby('Category').resample('W').mean()
    
    # the inverse of groupby, reset_index
    df2 = df2.reset_index()
    
    # set again the timestamp as index
    df2 = df2.set_index("ds")
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      相关资源
      最近更新 更多