多索引数据框中列之间的数学运算

wha*_*ada 4 python dataframe pandas

我有一个具有列multiindex的数据框,需要切片并在切片之间执行数学运算。

# 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)
Run Code Online (Sandbox Code Playgroud)

如果我想在各个列之间执行加/减运算,则可以使用索引切片并按如下方式进行:

df.loc[:,idx['three','foo']] - df.loc[:,idx['two','foo']]
Run Code Online (Sandbox Code Playgroud)

但是,如果我想使用更高级别的切片,它将无法正常工作并返回NaN:

# not working
df.loc[:,idx['three',:]] - df.loc[:,idx['two',:]]
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以使用df的更高级别的切片并仅添加/减去相应的列?我的数据框可能在multiindex中包含数百列。谢谢

jez*_*ael 5

如果需要输出中的MultiIndex rename用于相同级别的MultiIndex:

df = df.loc[:,idx['three',:]] - df.loc[:,idx['two',:]].rename(columns={'two':'three'})
print (df)
first      three          
second       foo       bar
A      -0.861579  3.157731
B      -1.944822  0.772031
C       2.649912  2.621137
Run Code Online (Sandbox Code Playgroud)

优点是可以将两个级别重命名为新的索引名称并加入原始索引:

df = (df.join(df.loc[:,idx['three',:]].rename(columns={'three':'four'}) - 
              df.loc[:,idx['two',:]].rename(columns={'two':'four'})))
print (df)
first        one                 two               three                four  \
second       foo       bar       foo       bar       foo       bar       foo   
A      -1.085631  0.997345  0.282978 -1.506295 -0.578600  1.651437 -0.861579   
B      -2.426679 -0.428913  1.265936 -0.866740 -0.678886 -0.094709 -1.944822   
C       1.491390 -0.638902 -0.443982 -0.434351  2.205930  2.186786  2.649912   

first             
second       bar  
A       3.157731  
B       0.772031  
C       2.621137  
Run Code Online (Sandbox Code Playgroud)

如有必要,请使用DataFrame.xs

df1 = df.xs('three', axis=1, level=0) - df.xs('two', axis=1, level=0)
print (df1)
second       foo       bar
A      -0.861579  3.157731
B      -1.944822  0.772031
C       2.649912  2.621137
Run Code Online (Sandbox Code Playgroud)

如果需要一级,一个可能的解决方案是MultiIndex.from_product

df1 = df.xs('three', axis=1, level=0) - df.xs('two', axis=1, level=0)
df1.columns = pd.MultiIndex.from_product([['new'], df1.columns], 
                                         names=['first','second'])
print (df1)
first        new          
second       foo       bar
A      -0.861579  3.157731
B      -1.944822  0.772031
C       2.649912  2.621137
Run Code Online (Sandbox Code Playgroud)