获取具有任何期望值的组

时间:2018-07-03 13:16:45

标签: python performance pandas unique pandas-groupby

gr = []
for i in range(12000): gr.extend([i] * 2)
np.random.seed(0)
df = pd.DataFrame({'gr': gr,
                   'col1': np.random.choice(200, 24000)})
anyOfThese = np.array([50, 60]) #randomly chosen
t = time()
out = df[df.groupby('gr')['col1'].transform(lambda x: np.any(np.in1d(np.array(x), anyOfThese))).astype(bool)].gr.unique()
print(round(time() - t,2))
>>> 1.87

我需要获取col1中具有两个所需值之一的所有组。

有没有办法更快地做到这一点?我需要重复相同的过程〜100k次。

2 个答案:

答案 0 :(得分:1)

boolean indexingisin一起使用进行过滤:

out = df.loc[df['col1'].isin(anyOfThese), 'gr'].unique()

或通过numpy.in1d检查成员身份:

out = df.loc[np.in1d(df['col1'], anyOfThese), 'gr'].unique()

时间

np.random.seed(218)

gr = []
for i in range(12000): 
    gr.extend([i] * 2)
np.random.seed(0)
df = pd.DataFrame({'gr': gr,
                   'col1': np.random.choice(200, 24000)})
anyOfThese = np.array([50, 60]) #randomly chosen

a = df[df.groupby('gr')['col1'].transform(lambda x: np.any(np.in1d(np.array(x), anyOfThese))).astype(bool)].gr.unique()
out = df.loc[df['col1'].isin(anyOfThese), 'gr'].unique()
print ((a == out).all())
True

In [314]: %timeit df[df.groupby('gr')['col1'].transform(lambda x: np.any(np.in1d(np.array(x), anyOfThese))).astype(bool)].gr.unique()
2.9 s ± 79.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [315]: %timeit df.loc[df['col1'].isin(anyOfThese), 'gr'].unique()
746 µs ± 32.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [316]: %timeit df.loc[np.in1d(df['col1'], anyOfThese), 'gr'].unique()
325 µs ± 14.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

答案 1 :(得分:1)

对于较大的数组,如果只有2个值,则可以检查每个值是否相等,并使用|(或)条件:

%timeit df.loc[(df['col1'].values == 50) | (df['col1'].values == 60), 'gr'].unique()
%timeit df.loc[np.in1d(df['col1'], anyOfThese), 'gr'].unique()

1000 loops, best of 3: 1.07 ms per loop
1000 loops, best of 3: 1.13 ms per loop

在Numpy 1.11.3 / Pandas 0.19.2 / Python 3.6.0上进行了测试。性能可能会因您的设置而异。用于测试的代码:

gr = []
for i in range(120000): gr.extend([i] * 2)

np.random.seed(0)
df = pd.DataFrame({'gr': gr,
                   'col1': np.random.choice(200, 240000)})

anyOfThese = np.array([50, 60])

%timeit df.loc[(df['col1'].values == 50) | (df['col1'].values == 60), 'gr'].unique()
%timeit df.loc[np.in1d(df['col1'], anyOfThese), 'gr'].unique()