根据列python将数据帧拆分为较小的数据帧

时间:2018-04-24 16:44:10

标签: python pandas

我有这个数据集:

raw data

我希望它看起来像这样:

weekly output

我知道我需要这样做:

df= df.groupby('city_id').resample('W').agg({'Quantity':'sum'}, loffset = pd.offsets.timedelta(days=-8))

获取每周聚合,但我需要按城市ID分组,按周聚合。

我的想法是我需要创建多个数据帧,每个城市ID,按日期聚合它们以使每周输出然后将它们重新连接在一起但我觉得有更好的方法来做到这一点。

2 个答案:

答案 0 :(得分:0)

试试这个:

df.groupby(['index', 'city_id'], as_index=False).sum()

这将对前两列进行分组,并总结其余两列。

答案 1 :(得分:0)

这解决了我的问题

output = df.groupby('city_id').resample('W').agg({'Quantity':'sum'}, loffset = pd.offsets.timedelta(days=-8))

相关问题