如何在pandas中groupby后取回索引

lea*_*ner 4 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
Run Code Online (Sandbox Code Playgroud)

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

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

Ale*_*der 5

我不确定一般的方法,但这对您的情况有效,因为您正在选择每个组的第一项(它也很容易处理最后一项)。事实上,由于 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
Run Code Online (Sandbox Code Playgroud)


WeN*_*Ben 2

尝试这个 ?

import pandas as pd
df = pd.DataFrame({'item_id': ['a', 'a', 'b', 'b', 'b', 'c', 'd'],
                   'cost': [1, 2, 1, 1, 3, 1, 5]})
t=df.drop_duplicates(subset=['item_id'],keep='first')
desired_row = t[t.cost == t.cost.max()]
df[~df.index.isin([desired_row.index[0]])]

Out[186]: 
   cost item_id
0     1       a
1     2       a
2     1       b
3     1       b
4     3       b
5     1       c
Run Code Online (Sandbox Code Playgroud)