使用多索引列进行计算

Making calculations with Multiindex columns

import pandas as pd
import numpy as np

midx = pd.MultiIndex(levels = [['A', 'B'], ['x', 'y', 'z']],
                     codes = [[1, 1, 1, 0, 0, 0], [2, 1, 0, 2, 1, 0]])

df = pd.DataFrame([[0.8, 0.4, 0.3],
                   [0.6, 1.0, 0.1],
                   [0.1, 0.9, 0.5],
                   [0.4, 1.3, 0.6],
                   [0.3, 0.7, 0.4],
                   [2.3, 1.0, 0.2]], columns = ['K', 'L', 'M'], index = midx)

print(df)

       K    L    M
B z  0.8  0.4  0.3
  y  0.6  1.0  0.1
  x  0.1  0.9  0.5
A z  0.4  1.3  0.6
  y  0.3  0.7  0.4
  x  2.3  1.0  0.2

我在这个结构中有多索引数据帧,这是我想要计算的:

df.loc['B', 'M'] = (df.loc['B', 'K'] + df.loc['A', 'K']).div(df.loc['B', 'L'] + df.loc['A', 'L']) 

作为这个过程的结果,所有值都是 NaN。我该如何解决这个问题?

有缺失值,因为adf.loc['B', 'M'].index的index不同,解决方法是create MultiIndex,例如通过 MultiIndex.from_product:

a = (df.loc['B', 'K'] + df.loc['A', 'K']).div(df.loc['B', 'L'] + df.loc['A', 'L']) 
a.index = pd.MultiIndex.from_product([['B'], a.index])
df.loc['B', 'M'] = a
print (df)
       K    L         M
B z  0.8  0.4  0.705882
  y  0.6  1.0  0.529412
  x  0.1  0.9  1.263158
A z  0.4  1.3  0.600000
  y  0.3  0.7  0.400000
  x  2.3  1.0  0.200000

另一个想法是转换为 numpy 数组,但如果 a 中的索引顺序与 df.loc['B', 'M'].index 不同,则应该以错误的顺序分配数据,这应该是有风险的:

df.loc['B', 'M'] = a.to_numpy()
print (df)
       K    L         M
B z  0.8  0.4  0.705882
  y  0.6  1.0  0.529412
  x  0.1  0.9  1.263158
A z  0.4  1.3  0.600000
  y  0.3  0.7  0.400000
  x  2.3  1.0  0.200000