marco
marco

Reputation: 129

Python - Pandas - Substracting sub-columns within an index column

Is there a simple way to Sub the same way I am doing Sum below?

In other words I would like to substract, within each index column, its two subcolumns.

import pandas as pd
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
df.sum(level=0, axis=1)

I find the last line very elegant, but obviously, this doesn't work... :

df.sub(level = 0,axis=1)

Upvotes: 1

Views: 72

Answers (1)

jezrael
jezrael

Reputation: 863351

You need xs for select each level of MultiIndex and sub:

print (df.xs('one', level=1, axis=1).sub(df.xs('two', level=1, axis=1)))
first       bar       baz       foo       qux
A      0.511199  1.684088 -1.377296  1.818127
B      0.421159  0.477186  0.777098 -1.265297
C      0.512711  2.262646 -0.435340  1.400147

Upvotes: 1

Related Questions