python - 如何在 pandas 的 groupby 之后取回索引

标签 python pandas

我试图在 groupby 之后从每个组中的第一条记录中找到具有最大值的记录,并将其从原始数据框中删除。

import pandas as pd
df = pd.DataFrame({'item_id': ['a', 'a', 'b', 'b', 'b', 'c', 'd'], 
                   'cost': [1, 2, 1, 1, 3, 1, 5]})
print df 
t = df.groupby('item_id').first() #lost track of the index
desired_row = t[t.cost == t.cost.max()]
#delete this row from df

         cost
item_id      
d           5

我需要跟踪 desired_row 并从 df 中删除这一行并重复该过程。

查找和删除 desired_row 的最佳方法是什么?

最佳答案

我不确定一般的方法,但这对你的情况有用,因为你正在拿每组的第一个项目(它也很容易在最后一个项目上工作)。事实上,由于 split-aggregate-combine 的一般性质,我认为如果不自己动手,这不会很容易实现。

gb = df.groupby('item_id', as_index=False)
>>> gb.groups  # Index locations of each group.
{'a': [0, 1], 'b': [2, 3, 4], 'c': [5], 'd': [6]}

# Get the first index location from each group using a dictionary comprehension.
subset = {k: v[0] for k, v in gb.groups.iteritems()}
df2 = df.iloc[subset.values()]
# These are the first items in each groupby.
>>> df2
   cost item_id
0     1       a
5     1       c
2     1       b
6     5       d

# Exclude any items from above where the cost is equal to the max cost across the first item in each group.
>>> df[~df.index.isin(df2[df2.cost == df2.cost.max()].index)]
   cost item_id
0     1       a
1     2       a
2     1       b
3     1       b
4     3       b
5     1       c

关于python - 如何在 pandas 的 groupby 之后取回索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45828354/

相关文章:

python - 值错误 : Received a null pointer

python - 在 Google App Engine 中使用 @ndb.tasklet 或 @ndb.synctasklet

python - Pandas df.describe() ,是否可以在不转置的情况下按行进行?

python - 如何在 DataFrame 中有效更新一组行值?如何使这个算法具有可扩展性?

python - 将 Pandas 列拆分为字符串后的两个空格

Python 使用 str 和 int 向列添加前导零

python - Selenium - Firefox 的 MoveTargetOutOfBoundsException

python - 用 1-24 小时而不是 0-23 小时解析日期时间

java - 尝试设置 Jython 解释器时出错

python - 间隔中的天数总和