I have a dataframe with column multiindex that I need to slice and perform math operations between the slices.
# sample df
idx=pd.IndexSlice
np.random.seed(123)
tuples = list(zip(*[['one', 'one', 'two', 'two', 'three', 'three'],['foo', 'bar', 'foo', 'bar', 'foo', 'bar']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 6), index=['A', 'B', 'C'], columns=index)
If I wanted to perform say addition/subtraction between individual columns, I could use index slice and do it like this:
df.loc[:,idx['three','foo']] - df.loc[:,idx['two','foo']]
However, if I want to use higher level slice it doesn't work and return NaNs:
# not working
df.loc[:,idx['three',:]] - df.loc[:,idx['two',:]]
Is there an easy way to use higher level slices of the df and add/subtract corresponding columns only? My dataframe potentially contains hundreds of columns in multiindex. Thanks