【问题标题】:pandas cross sectional indexing - select multiple columns熊猫横截面索引 - 选择多列
【发布时间】:2020-05-15 02:08:43
【问题描述】:

在pandas中切片多索引时如何选择count50%

import pandas as pd

df = pd.DataFrame({
    'foo': [1,2,3], 'bar':[4,5,6], 'dt':['2020-01-01', '2020-01-01', '2020-01-02']
})
df.groupby(['dt']).describe().loc[:, (slice(None), '50%'), (slice(None), 'count')]

失败:

IndexingError: Too many indexers

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用pd.IndexSlice

    ix = pd.IndexSlice
    df.groupby(['dt']).describe().loc[:, ix[:, ['count', '50%']]]
    
    Out[8]:
                 bar        foo
               count  50% count  50%
    dt
    2020-01-01   2.0  4.5   2.0  1.5
    2020-01-02   1.0  6.0   1.0  3.0
    

    【讨论】:

      【解决方案2】:

      另一种鲜为人知的方法是使用axis 参数到.loc,see docs

      df = pd.DataFrame({
          'foo': [1,2,3], 'bar':[4,5,6], 'dt':['2020-01-01', '2020-01-01', '2020-01-02']
      })
      df.groupby(['dt']).describe().loc(axis=1)[:, ['count','50%']]
      

      输出:

                   foo        bar     
                 count  50% count  50%
      dt                              
      2020-01-01   2.0  1.5   2.0  4.5
      2020-01-02   1.0  3.0   1.0  6.0
      

      【讨论】:

        猜你喜欢
        • 2018-09-27
        • 1970-01-01
        • 2020-04-27
        • 1970-01-01
        • 2018-05-28
        • 2014-10-01
        • 2015-01-20
        • 2020-01-12
        • 2020-07-17
        相关资源
        最近更新 更多