【问题标题】:Groupby two columns one of them is datetimeGroupby 两列,其中一列是日期时间
【发布时间】:2020-06-27 14:58:28
【问题描述】:

我有我想按两列分组的数据框,其中一列是日期时间类型。我该怎么做?

import pandas as pd 
import datetime as dt 

df = pd.DataFrame({ 


'a':np.random.randn(6),
'b':np.random.choice( [5,7,np.nan], 6),
'g':{1002,300,1002,300,1002,300}
'c':np.random.choice( ['panda','python','shark'], 6),

# some ways to create systematic groups for indexing or groupby
# this is similar to r's expand.grid(), see note 2 below
'd':np.repeat( range(3), 2 ),
'e':np.tile(   range(2), 3 ),

# a date range and set of random dates
'f':pd.date_range('1/1/2011', periods=6, freq='D'),
'g':np.random.choice( pd.date_range('1/1/2011', periods=365, 
                      freq='D'), 6, replace=False) 
})

【问题讨论】:

    标签: pandas dataframe datetime


    【解决方案1】:

    您可以使用pd.Grouper 指定groupby 指令。它可以与pd.DatetimeIndex索引一起使用,使用freq参数对指定频率的数据进行分组。

    假设你有这个数据框:

    df = pd.DataFrame(dict(
        a=dict(date=pd.Timestamp('2020-05-01'), category='a', value=1),
        b=dict(date=pd.Timestamp('2020-06-01'), category='a', value=2),
        c=dict(date=pd.Timestamp('2020-06-01'), category='b', value=6),
        d=dict(date=pd.Timestamp('2020-07-01'), category='a', value=1),
        e=dict(date=pd.Timestamp('2020-07-27'), category='a', value=3),
    )).T
    

    您可以将索引设置为date 列,它将转换为pd.DatetimeIndex。然后你可以在其他列中使用 pd.Grouper 。对于以下示例,我使用category 列。

    freq='M' 参数用于使用月份频率对索引进行分组。在pd.Grouper中可以使用string data series aliases的数量

    df.set_index('date').groupby([pd.Grouper(freq='M'), 'category'])['value'].sum()
    

    结果:

    date        category
    2020-05-31  a           1
    2020-06-30  a           2
                b           6
    2020-07-31  a           4
    Name: value, dtype: int64
    

    你的 mcve 的另一个例子:

    df.set_index('g').groupby([pd.Grouper(freq='M'), 'c']).d.sum()
    

    结果:

    g           c     
    2011-01-31  panda     0
    2011-04-30  shark     2
    2011-06-30  panda     2
    2011-07-31  panda     0
    2011-09-30  panda     1
    2011-12-31  python    1
    Name: d, dtype: int32
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多