在pandas中,按DatetimeIndex中的日期分组

2024-04-24 22:38:27 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下合成示例:

import pandas as pd
import numpy as np
np.random.seed(42)
ix = pd.date_range('2017-01-01', '2017-01-15', freq='1H')
df = pd.DataFrame(
    {
        'val': np.random.random(size=ix.shape[0]),
        'cat': np.random.choice(['foo', 'bar'], size=ix.shape[0])
    },
    index=ix
)

生成如下表格:

^{pr2}$

现在,我要计算每个类别和日期的实例数和平均值。在

下面的groupby,几乎是完美的:

df.groupby(['cat',df.index.date]).agg({'val': ['count', 'mean']})

返回:

                val
                count   mean
cat         
bar 2017-01-01  16  0.437941
    2017-01-02  16  0.456361
    2017-01-03  9   0.514388...

这个问题是,第二级索引变成了字符串,而不是date第一个问题:为什么会发生?我怎样才能避免呢?在

接下来,我尝试了groupby和{}的组合:

df.groupby('cat').resample('1d').agg({'val': 'mean'})

在这里,索引是正确的,但是我无法同时运行meancount聚合。这是第二个问题:为什么

df.groupby('cat').resample('1d').agg({'val': ['mean', 'count']})

不起作用?在

最后一个问题为索引获取聚合(使用两个函数)视图的方法是什么?在


Tags: importdfsizedateascountnprandom
1条回答
网友
1楼 · 发布于 2024-04-24 22:38:27

对于第一个问题,需要转换成datetimes,不带时间like

df1 = df.groupby(['cat',df.index.floor('d')]).agg({'val': ['count', 'mean']})
#df1 = df.groupby(['cat',df.index.normalize()]).agg({'val': ['count', 'mean']})

#df1 = df.groupby(['cat',pd.to_datetime(df.index.date)]).agg({'val'‌​: ['count', 'mean']})

print (df1.index.get_level_values(1))


DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04',
               '2017-01-05', '2017-01-06', '2017-01-07', '2017-01-08',
               '2017-01-09', '2017-01-10', '2017-01-11', '2017-01-12',
               '2017-01-13', '2017-01-14', '2017-01-01', '2017-01-02',
               '2017-01-03', '2017-01-04', '2017-01-05', '2017-01-06',
               '2017-01-07', '2017-01-08', '2017-01-09', '2017-01-10',
               '2017-01-11', '2017-01-12', '2017-01-13', '2017-01-14',
               '2017-01-15'],
              dtype='datetime64[ns]', freq=None)

。。。因为dates是python对象:

^{pr2}$

第二个问题-在我看来,这是错误还是尚未实现,因为只在agg中使用一个函数名:

df2 = df.groupby('cat').resample('1d')['val'].agg('mean')
#df2 = df.groupby('cat').resample('1d')['val'].mean()
print (df2)
cat            
bar  2017-01-01    0.437941
     2017-01-02    0.456361
     2017-01-03    0.514388
     2017-01-04    0.580295
     2017-01-05    0.426841
     2017-01-06    0.642465
     2017-01-07    0.395970
     2017-01-08    0.359940
...
... 

但是与^{cd4>}一起工作old way

df2 = df.groupby('cat').apply(lambda x: x.resample('1d')['val'].agg(['mean','count']))
print (df2)
                    mean  count
cat                            
bar 2017-01-01  0.437941     16
    2017-01-02  0.456361     16
    2017-01-03  0.514388      9
    2017-01-04  0.580295     12
    2017-01-05  0.426841     12
    2017-01-06  0.642465      7
    2017-01-07  0.395970     11
    2017-01-08  0.359940      9
    2017-01-09  0.564851     12
    ...
    ...

相关问题 更多 >