My dataframes are in a "wide" format, such that columns contain data for different entities, and rows are dates, e.g. product costs through time:
import pandas as pd
cost = pd.DataFrame([[10,20,30,40],[11,22,33,44],[111,222,333,444]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
Knife Fork Spoon Spatula
2022-01-01 10 20 30 40
2022-01-02 11 22 33 44
2022-01-03 111 222 333 444
I have a similar dataframe that places each data point in one of two groups (1 or 2):
grp = pd.DataFrame([[1,2,1,2],[1,1,2,2],[2,1,1,2]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
Knife Fork Spoon Spatula
2022-01-01 1 2 1 2
2022-01-02 1 1 2 2
2022-01-03 2 1 1 2
I want to do an aggregate groupby-style mean on each of the groups for each date. As such, this is my desired output, showing the averages for groups 1 and 2:
avg = pd.DataFrame([[(10+30)/2,(20+40)/2],[(11+22)/2,(33+44)/2],[(111+444)/2,(222+333)/2]], columns=[1,2], index=pd.date_range('2022-01-01','2022-01-03'))
1 2
2022-01-01 20.0 30.0
2022-01-02 16.5 38.5
2022-01-03 277.5 277.5
I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).
It seems to me there must be a better way to aggregate this kind of "wide" data? My actual data is way bigger (and with more groups), hence a desire for efficiency.
How can I most efficiently gain my desired output?