对于第一个问题需要转换为datetime
没有时间like https://stackoverflow.com/a/45943387/2901002:
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)
... 因为date
s 是 python 对象:
df1 = df.groupby(['cat',df.index.date]).agg({'val': ['count', 'mean']})
print (type(df1.index.get_level_values(1)[0]))
<class 'datetime.date'>
第二个问题 - 在我看来这是错误或尚未实现,因为在中使用一个函数名称agg
only:
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
...
...
但工作old way http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#groupby-syntax-with-window-and-resample-operations with apply
:
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
...
...