【发布时间】:2017-08-30 15:59:02
【问题描述】:
考虑以下综合示例:
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
)
生成如下形式的表格:
cat val
2017-01-01 00:00:00 bar 0.374540
2017-01-01 01:00:00 foo 0.950714
2017-01-01 02:00:00 bar 0.731994
2017-01-01 03:00:00 bar 0.598658
2017-01-01 04:00:00 bar 0.156019
现在,我想计算每个类别和日期的实例数和平均值。
以下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和resample的组合:
df.groupby('cat').resample('1d').agg({'val': 'mean'})
在这里,索引是正确的,但我无法同时运行 mean 和 count 聚合。这是第二个问题:为什么
df.groupby('cat').resample('1d').agg({'val': ['mean', 'count']})
没有用?
最后一个问题什么是获取聚合(使用两个函数)视图和的干净方法,索引类型为date?
【问题讨论】: