如果我有这个数据框
import pandas as pd
tuples_index = [(1,1990), (2,1999), (2,2002), (3,1992), (3,1994), (3,1996)]
index = pd.MultiIndex.from_tuples(tuples_index, names=['id', 'FirstYear'])
df = pd.DataFrame([2007, 2006, 2006, 2000, 2000, 2000], index=index, columns=['LastYear'] )
df
Out[2]:
LastYear
id FirstYear
1 1990 2007
2 1999 2006
2002 2006
3 1992 2000
1994 2000
1996 2000
我想获取数据框的一个子集,其中基于 id 的组长于一个,我可以这样做,但速度很慢:
%timeit df.groupby(level=0).filter(lambda x: len(x) > 1)
1000 loops, best of 3: 1.36 ms per loop
我的 df 有数千万行和大量的组(大多数组都是 len 1)所以时间加起来。我可以通过这种方式更快地获得 bool 索引器:
%timeit df.groupby(level=0).size() > 1
1000 loops, best of 3: 364 µs per loop
但是 bool 索引器只有 id 作为它的索引:
id
1 False
2 True
3 True
我想我可能提供了比必要更多的上下文,但是我如何使用具有单个索引的 bool 索引器从具有 MultiIndex 的数据帧中获取子集?期望的输出是:
LastYear
id FirstYear
2 1999 2006
2002 2006
3 1992 2000
1994 2000
1996 2000
最佳答案
关于python - 使用单索引 bool 索引器获取 MultiIndex Pandas DataFrame 的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497487/