N = 300
S = ['AR1', 'PO1', 'AR2', 'PO2', 'AR3', 'PO3']
df = pd.DataFrame({'X': np.random.uniform(-1, 1, N), 'Y': np.random.uniform
    (-1, 1, N), 'S': np.random.choice(S, N)})
df['bins_X'] = df.groupby('S')['X'].apply(pd.qcut, q=20, labels=np.arange(20))

def func(df):
    df1 = df.groupby(['S', 'bins_X']).sum()
new_cols = list(zip(df1.columns.get_level_values(0)))
df1.columns = pd.MultiIndex.from_tuples(new_cols)
return df1
df1 = func(df)
Selecting rows in a MultiIndexed dataframe