pandas groupby中的最大最小日期
我有一个数据表,长得像这样:
data = {'index': ['2014-06-22 10:46:00', '2014-06-24 19:52:00', '2014-06-25 17:02:00', '2014-06-25 17:55:00', '2014-07-02 11:36:00', '2014-07-06 12:40:00', '2014-07-05 12:46:00', '2014-07-27 15:12:00'],
'type': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'C'],
'sum_col': [1, 2, 3, 1, 1, 3, 2, 1]}
df = pd.DataFrame(data, columns=['index', 'type', 'sum_col'])
df['index'] = pd.to_datetime(df['index'])
df = df.set_index('index')
df['weekofyear'] = df.index.weekofyear
df['date'] = df.index.date
df['date'] = pd.to_datetime(df['date'])
type sum_col weekofyear date
index
2014-06-22 10:46:00 A 1 25 2014-06-22
2014-06-24 19:52:00 B 2 26 2014-06-24
2014-06-25 17:02:00 C 3 26 2014-06-25
2014-06-25 17:55:00 A 1 26 2014-06-25
2014-07-02 11:36:00 B 1 27 2014-07-02
2014-07-06 12:40:00 C 3 27 2014-07-06
2014-07-05 12:46:00 A 2 27 2014-07-05
2014-07-27 15:12:00 C 1 30 2014-07-27
我想按照一年中的周数来分组,然后把某一列的数值加起来。此外,我还需要找出这一周的最早和最晚日期。前面的部分比较简单:
gb = df.groupby(['type', 'weekofyear'])
gb['sum_col'].agg({'sum_col' : np.sum})
我试着用这个方法找最早和最晚的日期,但没有成功:
gb = df.groupby(['type', 'weekofyear'])
gb.agg({'sum_col' : np.sum,
'date' : np.min,
'date' : np.max})
要怎么找到出现的最早和最晚日期呢?
3 个回答
6
还有一种可能的解决方案,可以让你对生成的列名有更多的控制权:
gb = df.groupby(['type', 'weekofyear'])
gb.agg(
sum_col=('sum_col', np.sum),
first_date=('date', np.min),
last_date=('date', np.max)
).reset_index()
31
简单的代码可以是
df.groupby([key_field]).agg({'time_field': [np.min,np.max]})
这里的 key_field 可以是事件 ID,而 time_field 可以是时间戳字段。
93
你需要把作用于同一列的函数结合起来,像这样:
In [116]: gb.agg({'sum_col' : np.sum,
...: 'date' : [np.min, np.max]})
Out[116]:
date sum_col
amin amax sum
type weekofyear
A 25 2014-06-22 2014-06-22 1
26 2014-06-25 2014-06-25 1
27 2014-07-05 2014-07-05 2
B 26 2014-06-24 2014-06-24 2
27 2014-07-02 2014-07-02 1
C 26 2014-06-25 2014-06-25 3
27 2014-07-06 2014-07-06 3
30 2014-07-27 2014-07-27 1