到目前为止,我拥有的是一个包含以下列的正常事务数据帧:
store | item | year | month | day | sales
"年份"可以是 2015、2016、2017。
这样,我创建了一个摘要数据框:
store_item_years = df.groupby(
['store','item','year'])['sales'].agg(
[np.sum, np.mean, np.std, np.median, np.min, np.max]).unstack(
fill_value=0)
最后一个结果是具有 2 个级别的多索引,如下所示:
sum mean
year | 2015 | 2016 | 2017 | 2015 | 2016 | 2017 | ...
store | item sum1 ... ... mean1 mean2 ... | ...
现在我想将摘要表合并回事务表:
store | item | year | month | day | sales | + | sum+'by'+year | mean+'by'+year
2015 sum1 mean1
2016 sum2 mean2
2017 ... ...
我正在尝试与以下内容合并:
df = pd.merge(df, store_item_years,
left_on=['store', 'item', 'year'],
right_on=['store', 'item', 'year'],
how='left')
这会导致以下错误:
KeyError: 'year'
有什么想法吗?我只是在分组。我还没有研究过数据透视表。
请记住,问题已简化。store_item组合的数量为 200+K,其他分组组合的数量为 300+ 列。但始终相同的原则。
提前非常感谢。
我认为您需要首先删除unstack
然后使用join
进行左连接:
store_item_years = df.groupby(
['store','item','year'])['sales'].agg(
[np.sum, np.mean, np.std, np.median, np.min, np.max])
df = df.join(store_item_years, on=['store','item','year'])
找到了罪魁祸首。删除了 .unstack((。
store_item_years = df.groupby(
['store','item','year'])['sales'].agg(
[np.sum, np.mean, np.std, np.median, np.min, np.max])
以下内容以保持上下文:
store_item_years.columns = store_item_years.columns+'_by_year'
并像这样合并:
pd.merge(df, store_item_years.reset_index(),
left_on=['store', 'item', 'year'],
right_on=['store', 'item', 'year'],
how='left')