Python - Pandas - 减去索引列中的子列

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

是否有一种简单的方法可以像我在下面做 Sum 一样使用 Sub?

换句话说,我想在每个索引列中减去它的两个子列。

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)

我觉得最后一行非常优雅,但显然,这行不通...:

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

你需要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