熊猫横截面索引-选择多列

时间:2020-05-14 17:47:42

标签: python 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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

另一种鲜为人知的方法是对axissee docs使用.loc参数:

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
相关问题