Python 分组而不丢失列

Python 分组而不丢失列,python,pandas,dataframe,Python,Pandas,Dataframe,我的数据框有问题。我有一个有三列的数据框,前两列是标识符(str),第三列是数字 我想对它进行分组,以便得到第一列,第三列作为max,第二列对应于第三列进行索引 这不太清楚,让我们举个例子。我的数据框看起来像: id1 id2 amount 0 first_person first_category 18 1 first_person second_category 37 2 second_

我的数据框有问题。我有一个有三列的数据框,前两列是标识符(str),第三列是数字

我想对它进行分组,以便得到第一列,第三列作为max,第二列对应于第三列进行索引

这不太清楚,让我们举个例子。我的数据框看起来像:

    id1              id2                amount
0   first_person     first_category     18
1   first_person     second_category    37
2   second_person    first_category     229
3   second_person    third_category     23
如果需要,请输入代码:

df = pd.DataFrame([['first_person','first_category',18],['first_person','second_category',37],['second_person','first_category',229],['second_person','third_category',23]],columns = ['id1','id2','amount'])
我想得到:

    id1              id2                amount
0   first_person     second_category    37
1   second_person    third_category     229
我尝试了groupby方法,但它使我失去了第二列:

result = df.groupby(['id1'],as_index=False).agg({'amount':np.max})
IIUC您要在“id1”上确定金额最大的行,并使用该行索引到原始df中:

In [9]:
df.loc[df.groupby('id1')['amount'].idxmax()]

Out[9]:
             id1              id2  amount
1   first_person  second_category      37
2  second_person   first_category     229

df.groupby(['id1',as_index=False).max()
-这就是你想要的吗?问题是,并不是每次最后一个类别对应最大的金额(*编辑我的帖子以澄清)@MaxU都认为它也是第一个类别,但它会返回
id2
amount
的最大值,不是最大金额为
amount
的行。但您必须定义规则-在
id2
列上应用哪个聚合函数我希望每个人都有金额最大的类别。(以及相应的金额)