基于MultiColumn二级的圆柱

Round columns based on second level of MultiColumn

我有一个 table 看起来像这样:

>>> df.head()
Out[13]: 
                                v                   u                      
                             init    change  integral      init    change   
     foo          bar                                                     
baseline          NaN    0.025054  0.858122  0.017930  0.048435  1.091943   
       a          10.0   0.025042  0.856307  0.017546  0.047815  1.100351   
                  50.0   0.025008  0.856681  0.010052  0.048252  1.056658   
       b          1.0    0.025045  0.858044  0.015635  0.047135  1.091384   
                  2.0    0.025048  0.855388  0.016115  0.047324  1.087964 

现在我想select基于列的第二级标签的列,并四舍五入。

我可以使用 xs 访问它们:df.xs('init', 1, 1)。但是,我自然不能用xs来代替值:

>>> df.xs('init', 1, 1) = df.xs('init', 1, 1).round(decimals=3)
  File "<ipython-input-12-47c16e5011a3>", line 1
    df.xs('init', 1, 1) = df.xs('init', 1, 1).round(decimals=3)
SyntaxError: can't assign to function call

到这里怎么走?

考虑数据框:

df = pd.DataFrame(np.arange(8).reshape(2, 4),
                  ['a', 'b'],
                  pd.MultiIndex.from_product([['A', 'B'], ['One', 'Two']]))

df

使用pd.IndexSlice

df.loc[:, pd.IndexSlice[:, 'Two']] *= 3

df

在这种情况下,pd.IndexSlice[:, 'Two'] 指定了第一级的所有元素,'Two' 指定了第二级的所有元素。使用 loc 允许我们分配给 df.