Skip to main content
 首页 » 编程设计

python之Groupby 不丢失列

2025年04月02日21落叶无声

我在使用 pandas 数据框时遇到问题。我有一个包含三列的数据框,前两列是标识符 (str),第三列是数字。

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

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

    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你要groupby在 'id1' 上并使用 idxmax 确定数量最大的行并用它来索引你原来的 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