使用部分索引元组列表分割多索引数据帧的最佳方法是什么?

2024-04-25 15:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用部分匹配的索引或元组列表对数据帧进行切片。你知道吗

_ix = [('foo','a', 1), ('foo','a', 2), ('foo','b', 1), 
       ('foo','b', 2), ('foo','c', 1), ('foo','c', 2)]
df = pd.DataFrame(np.ones((6, 1)), index=pd.MultiIndex.from_tuples(_ix))
print(df)

           0
foo a 1  1.0
      2  1.0
    b 1  1.0
      2  1.0
    c 1  1.0
      2  1.0

给定如下查询索引:

q_ix = [('foo', 'a'), ('foo', 'c')]

我想获得

           0
foo a 1  1.0
      2  1.0
    c 1  1.0
      2  1.0

我可以通过使用pd.concat和一个列表理解得到这个。。。你知道吗

df_sliced = pd.concat([df.loc[(*x, slice(None)), :] for x in q_ix])

…但当我的查询索引很大时,这会非常笨拙。没有更好的办法了吗?你知道吗


Tags: 数据fromdataframedf列表indexfoonp
3条回答

您可以尝试在掩码上使用index.droplevelisin,以及.loc,如下所示

n = df.index.droplevel(2).isin(q_ix)

Out[75]: array([ True,  True, False, False,  True,  True])

df.loc[n]

Out[76]:
           0
foo a 1  1.0
      2  1.0
    c 1  1.0
      2  1.0

pandas使用pd.IndexSlice

import pandas as pd

idx = pd.IndexSlice


df.loc[idx[:, ['a', 'c']], :] # Can use 'foo' instead of : on the first lvl

输出

           0
foo a 1  1.0
      2  1.0
    c 1  1.0
      2  1.0

它读取沿第一级(:)的所有内容,然后在第二级抓取["a", "c"]。我们把它括在idx中,以表明它是一个切片。最后,最后一个:告诉我们需要所有列。你知道吗

这里有一个方法

df.reset_index(level=2).loc[q_ix].set_index('level_2',append=True)
                 0
      level_2     
foo a 1        1.0
      2        1.0
    c 1        1.0
      2        1.0

相关问题 更多 >