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)
是否有一种简单的方法可以像我在下面做 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)