访问基于部分多索引的系列。

问题描述 投票:0回答:1

我有一个(很长的)pandas系列,有一个4层的MultiIndex,类似于。

objs = ['car', 'bicycle', 'plane']
trials = ['trial A', 'trial B']
moves = [f'mov{i}' for i in range(1,11)]
multi = pd.MultiIndex.from_product([objs, trials, moves, range(10)], names=['obj', 'try', 'mov', 'time'])
s = pd.Series(np.random.rand(len(multi)))

我也有一个匹配的图元组列表 一些 obj'和'mov'下的指数。例如(实际上要长得多)。

idxs = [('car','mov1'), ('car','mov6'), ('plane','mov1')]

有没有办法让所有的记录 s 的指数 multi 包含在 idxs? 我希望在做这个工作的时候不要重新索引切片系列,因为我说过它非常长,那样效率会很低。我阅读了 当地 &amp。xs但这两个都不是我所需要的。

python pandas multi-index
1个回答
0
投票

一种方法是使用列表理解与 pd.DataFrame.query。

pd.concat([s.to_frame().query('obj == @i and mov == @j') for i, j in idxs])

-1
投票
def eligible(line):
    if (line[0]=='car' and line[2] in ['mov1', 'mov6']) or (line[0]=='plane' and line[2] == 'mov1'):
        return True
    else:
        return False

s[[i for i, line in enumerate(multi) if eligible(line)]]
© www.soinside.com 2019 - 2024. All rights reserved.