pandas.core.groupby.DataFrameGroupBy.idxmin() is very slow , how can i make my cod faster?

匆匆过客 提交于 2019-12-24 07:30:24

问题


i am trying to do same action as SQL group by and take min value :

select id,min(value) ,other_fields...
from table
group by ('id')

i tried :

dfg = df.groupby('id', sort=False)
idx = dfg['value'].idxmin()
df = df.loc[idx, list(df.columns.values)]

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmin.html but line 2 the idxmin() is taking more than half hour on ~4M columns in df where the group by takes less than 1 second , what am i missing is it suppose to take that long ? how can make this process faster ? will it be faster in pure SQL ?


回答1:


use alternative with DataFrame.sort_values and DataFrame.drop_duplicates:

df1 = df.sort_values(by=['value']).drop_duplicates('id', keep='first')


来源:https://stackoverflow.com/questions/55932560/pandas-core-groupby-dataframegroupby-idxmin-is-very-slow-how-can-i-make-my-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!