gpt4 book ai didi

python - 为什么pandas nlargest 比我的慢?

转载 作者:行者123 更新时间:2023-12-04 12:16:11 24 4
gpt4 key购买 nike

我有一个数据框

            ID  CAT    SCORE
0 0 0 8325804
1 0 1 1484405
... ... ... ...
1999980 99999 0 4614037
1999981 99999 1 1818470

我按 ID 对数据进行分组的地方并想知道每个 ID 得分最高的 2 个类别。我可以看到两个解决方案:
df2 = df.groupby('ID').apply(lambda g: g.nlargest(2, columns='SCORE'))

或手动将其转换为元组列表,对元组进行排序,删除除两个 ID 之外的每个 ID,然后转换回数据帧。第一个应该比第二个快得多,但我观察到手动解决方案要快得多。

为什么手动 nlargest 比 pandas 解决方案快?

MVCE
import numpy as np
import pandas as pd
import time


def create_df(n=10**5, categories=20):
np.random.seed(0)
df = pd.DataFrame({'ID': [id_ for id_ in range(n) for c in range(categories)],
'CAT': [c for id_ in range(n) for c in range(categories)],
'SCORE': np.random.randint(10**7, size=n * categories)})
return df


def are_dfs_equal(df1, df2):
columns = sorted(df1.columns)
if len(df1.columns) != len(df2.columns):
return False
elif not all(el1 == el2 for el1, el2 in zip(columns, sorted(df2.columns))):
return False
df1_list = [tuple(x) for x in df1[columns].values]
df1_list = sorted(df1_list, reverse=True)
df2_list = [tuple(x) for x in df2[columns].values]
df2_list = sorted(df2_list, reverse=True)
is_same = df1_list == df2_list
return is_same


def manual_nlargest(df, n=2):
df_list = [tuple(x) for x in df[['ID', 'SCORE', 'CAT']].values]
df_list = sorted(df_list, reverse=True)
l = []
current_id = None
current_id_count = 0
for el in df_list:
if el[0] != current_id:
current_id = el[0]
current_id_count = 1
else:
current_id_count += 1
if current_id_count <= n:
l.append(el)
df = pd.DataFrame(l, columns=['ID', 'SCORE', 'CAT'])
return df

df = create_df()

t0 = time.time()
df2 = df.groupby('ID').apply(lambda g: g.nlargest(2, columns='SCORE'))
t1 = time.time()
print('nlargest solution: {:0.2f}s'.format(t1 - t0))

t0 = time.time()
df3 = manual_nlargest(df, n=2)
t1 = time.time()
print('manual nlargest solution: {:0.2f}s'.format(t1 - t0))
print('is_same: {}'.format(are_dfs_equal(df2, df3)))


nlargest solution: 97.76s
manual nlargest solution: 4.62s
is_same: True

最佳答案

我想你可以使用这个:

df.sort_values(by=['SCORE'],ascending=False).groupby('ID').head(2)

这与在 pandas groupby 上使用 Sort/head 函数的手动解决方案相同。
t0 = time.time()
df4 = df.sort_values(by=['SCORE'],ascending=False).groupby('ID').head(2)
t1 = time.time()
df4_list = [tuple(x) for x in df4[['ID', 'SCORE', 'CAT']].values]
df4_list = sorted(df4_list, reverse=True)
is_same = df3_list == df4_list
print('SORT/HEAD solution: {:0.2f}s'.format(t1 - t0))
print(is_same)


SORT/HEAD solution: 0.08s
True

时间
77.9 ms ± 7.91 ms per loop (mean ± std. dev. of 7 runs, 10 loops each).

至于为什么 nlargest比其他解决方案慢?,我想为每个组调用它会产生开销( %prun 在 30.293 秒内显示 15764409 个函数调用(15464352 个原始调用))。

对于此解决方案(0.078 秒内 1533 次函数调用(1513 次原始调用))

关于python - 为什么pandas nlargest 比我的慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54090952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com