import pandas as pd
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))
a = [['A', 'b1', '01/01/2015', 3],
['A', 'b1', '01/02/2015', 4],
['A', 'b1', '01/03/2015', 2],
['A', 'b2', '01/01/2015', 7],
['A', 'b2', '01/02/2015', 2],
['A', 'b2', '01/03/2015', 1],
['A', 'b3', '01/01/2015', 6],
['A', 'b3', '01/02/2015', 3],
['A', 'b3', '01/03/2015', 1]]
df = pd.DataFrame(a, columns=['Company', 'Brand', 'Date', 'Amount'])
ps = powerset(['b1', 'b2', 'b3'])
new_df = pd.DataFrame()
for s in ps:
view = df[df.Brand.isin(s)].groupby(['Company', 'Date']).mean()
view['Brand'] = '_'.join(s)
new_df = new_df.append(view)
The result is as follows:
Amount Brand
Company Date
A 01/01/2015 3.000000 b1
01/02/2015 4.000000 b1
01/03/2015 2.000000 b1
01/01/2015 7.000000 b2
01/02/2015 2.000000 b2
01/03/2015 1.000000 b2
01/01/2015 6.000000 b3
01/02/2015 3.000000 b3
01/03/2015 1.000000 b3
01/01/2015 5.000000 b1_b2
01/02/2015 3.000000 b1_b2
01/03/2015 1.500000 b1_b2
01/01/2015 4.500000 b1_b3
01/02/2015 3.500000 b1_b3
01/03/2015 1.500000 b1_b3
01/01/2015 6.500000 b2_b3
01/02/2015 2.500000 b2_b3
01/03/2015 1.000000 b2_b3
01/01/2015 5.333333 b1_b2_b3
01/02/2015 3.000000 b1_b2_b3
01/03/2015 1.333333 b1_b2_b3