简体   繁体   English

更有效的方法来迭代 groupby Pandas 数据框?

[英]More efficient way to iterate groupby Pandas dataframe?

I have this snippet code that groupby column ID from a pandas dataframe and appends in a result dataframe all the top salaries from a unique ID.我有这个片段代码,它从熊猫数据框中按列ID分组,并将来自唯一 ID 的所有最高工资附加到结果数据框中。 The code works but is kind of slow with larger files.该代码有效,但对于较大的文件来说有点慢。 I was wondering if someone could suggest a more efficient way.我想知道是否有人可以提出更有效的方法。

groupe = df.groupby("ID")
t = (group.sort_values(by="Salary", ascending=False)[:1] for yr, group in groupe)
result = pd.DataFrame() 
     for i in t:
        result = result.append(i)
df.groupby('ID').max()

You can then select the salaries column.然后,您可以选择工资列。

Edit编辑

If you want to retain all other columns, even the non-numerical, this should do the job:如果您想保留所有其他列,即使是非数字列,也应该这样做:

df.sort_values(by="Salary", ascending=False).groupby('ID').first() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 pandas 中使用 groupby() 创建新的 dataframe 的更有效方法? - More efficient way for creating new dataframe using groupby() in pandas? 有没有更有效的方法来迭代数据帧? - is there a more efficient way to iterate over a dataframe? 在 Pandas DataFrame 中匹配字符串的更有效方法 - More efficient way to match strings in a Pandas DataFrame 在 pandas 中使用 groupby 获得比例的更有效方法 - more efficient way to get proportion of ones using groupby in pandas Pandas 基于 groupby 掩码过滤数据帧的最有效方法 - Pandas most efficient way to filter dataframe based on groupby mask 最有效的分组方式 => 聚合熊猫中的大型数据框 - Most efficient way to groupby => aggregate for large dataframe in pandas 如何使用 Numpy.vectorize 以有效的方式迭代 Pandas 数据帧? - How iterate in a efficient way over Pandas dataframe with Numpy.vectorize? Pandas:在没有for循环的情况下更新pandas数据框中列的更有效方法 - Pandas: More efficient way to update a column in pandas dataframe without a for loop 将熊猫数据帧转换为位图的更有效方法是什么? - What's a more efficient way to convert pandas dataframe to a bit map? 在熊猫数据框列中查找最高值的更有效方法 - More efficient way to find top values in pandas dataframe column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM