2017-11-18 7 views
1

私がこれまで持っていることは、次の列を持つ通常のトランザクションデータフレームです:単一レベルのデータフレーム内の値のマルチレベルのデータフレームを結合する方法

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つのレベル、とマルチインデックスの最後の結果:

0123今
   sum     mean 
     year | 2015 | 2016 | 2017 | 2015 | 2016 | 2017 | ... 
store | item sum1 ... ... mean1 mean2 ... | ...  

私は、トランザクション1に戻ってサマリー表をマージしたい:私は次のようにマージしようとしています

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を使用する必要があると思う

答えて

1

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']) 
+0

ありがとう!はい、私はちょうどそれに気付きました。あなたが私を殴ってくれるので、私はあなたの答えを受け入れるでしょう:) – user319436

0

は犯人を見つけました。 .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') 
関連する問題