【问题标题】:Round columns based on second level of MultiColumn基于第二级MultiColumn的圆形柱子
【发布时间】:2016-11-14 17:57:51
【问题描述】:

我有一个如下所示的表格:

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

现在我想根据列的第二级标签选择列,并将它们四舍五入。

我可以使用 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

这里怎么走?

【问题讨论】:

    标签: python pandas dataframe multi-index


    【解决方案1】:

    考虑数据框:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 2022-10-16
      • 2019-05-24
      • 1970-01-01
      相关资源
      最近更新 更多