假设我已经得到了a的分组索引列表,dataframe
并且我想使用groupby
或其他函数来获得子数据帧。我知道我可以使用isin
像[df[df.index.isin(group)] for group in grouplist]
查询数据框几次,但它似乎是非常缓慢的。我怎样才能更有效地分组?
grouplist = [[1],[29, 30, 31],[40],[46, 47, 48, 49],[58, 59],[68, 69, 70],[99, 100, 101],[103]]
看来您需要loc
:
[df.loc[group] for group in grouplist]
编辑:
对于列中的检查值可以更快地使用:
[df[np.in1d(df.A, group)] for group in grouplist]
要么:
[df[df.A.isin(group)] for group in grouplist]
时间:
np.random.seed(123)
N = 100000
df = pd.DataFrame({'A': np.random.randint(150, size=N),
'B':np.random.rand(N)})
#print (df)
grouplist = [[1],[29, 30, 31],[40],[46, 47, 48, 49],
[58, 59],[68, 69, 70],[99, 100, 101],[103]]
def a(df):
df = df.set_index('A')
return [df.loc[group] for group in grouplist]
def b(df):
return [df[df.A.isin(group)] for group in grouplist]
def c(df):
return [df[np.in1d(df.A, group)] for group in grouplist]
In [84]: %timeit (a(df))
10 loops, best of 3: 117 ms per loop
In [85]: %timeit (b(df))
100 loops, best of 3: 18.3 ms per loop
In [86]: %timeit (c(df))
100 loops, best of 3: 5.44 ms per loop
警告:
性能实际上取决于DataFrame的数据大小和in中的组中的值数grouplist
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句