【问题标题】:Slice pandas multiindex dataframe using list of index values [duplicate]使用索引值列表对 pandas 多索引数据框进行切片 [重复]
【发布时间】:2018-03-12 08:08:06
【问题描述】:

我有一个看起来像的多索引数据框

uid tid 文本

abc x t1

bcd y t2

uidtid 是索引。我有一个 uid 列表,并且想要获取与该列表中的 uids 对应的行,但保留第二级索引值 (tid)。我想在不运行任何显式循环的情况下做到这一点。这可能吗?

【问题讨论】:

    标签: python pandas slice multi-index


    【解决方案1】:

    数据:

    L = ['abc', 'bcd']
    
    print (df)
             text
    uid  tid     
    abc  x     t1
    abc1 x     t1
    bcd  y     t2
    

    1.slicers

    idx = pd.IndexSlice
    df1 = df.loc[idx[L,:],:]
    

    2.boolean indexing + 带有get_level_values 的掩码 + isin:

    df1 = df[df.index.get_level_values(0).isin(L)]
    

    3.querydocs

    df1 = df.query('@L in uid')
    
    print (df1)
            text
    uid tid     
    abc x     t1
    bcd y     t2
    

    【讨论】:

    • 感谢@jezrael。使用方法一,我得到“MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)”错误。但是2有效。哪个效率最高?我有一个巨大的数据框。
    • 最快的是先按df = df.sort_index()排序,然后用第一种方法。 sorting 解释'In 97'
    猜你喜欢
    • 2021-12-07
    • 2014-05-02
    • 2020-04-12
    • 1970-01-01
    • 2019-11-14
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多