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

标签 python pandas dataframe

我有一个包含列多索引的数据框,我需要对其进行切片并在切片之间执行数学运算。

# 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)

如果我想在各个列之间执行加法/减法,我可以使用索引切片并这样做:

df.loc[:,idx['three','foo']] - df.loc[:,idx['two','foo']]

但是,如果我想使用更高级别的切片,它就不起作用并返回 NaN:

# not working
df.loc[:,idx['three',:]] - df.loc[:,idx['two',:]]

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

最佳答案

如果需要 MultiIndex 在输出中使用 rename 相同级别的 od 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

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

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  

如果不需要,使用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

如果需要第一级,可能的解决方案是 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

关于python - 多索引数据框中列之间的数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55020741/

相关文章:

python - 如何绘制 Pandas 列的散点子图

python - Pandas Groupby 返回平均但是!排除 NaN

python - 为所有类方法打印 python 文档字符串

python - 根据信号所在位置调整 xrange

Python pandas 交叉选择相当于 .loc 和切片

python - 将数据框 reshape 为具有无限行并在没有值的情况下填充零的数据框

python - fillna 没有给出预期的结果

python os.walk 显示混合的 windows 和 unix 路径

Python Pandas 子集十六进制字符串,转换为十进制

python - 通过使用另一列中的值在字典中查找值,将新列添加到 Pandas DataFrame