在每个组中获取最大值,通过组总和

4
import pandas as pd
import numpy as np
from datetime import datetime
df = pd.DataFrame(
    { 
        'Date' : np.random.choice(pd.date_range(datetime(2020,1,1),periods=5),20),
        'Product' : np.random.choice(['Milk','Brandy','Beer'],20)   ,    
     'Quantity' : np.random.randint(10,99,20)
        
    }  
)
df.groupby(['Date','Product']).sum()

这将给出:

enter image description here

我想要获得每组总和的最大值,有什么最好的方法吗?

我的随机样本值的预期结果如下。

enter image description here

我该如何实现这个结果。

3个回答

4
你可以使用另一个groupby,这次在你的索引的第一层(产品)上进行,并获取最大值:
df.groupby(['Date','Product']).sum().groupby(level=1).max()

         Quantity
Product          
Beer          160
Brandy         97
Milk          245

要获取日期,请使用 sort_valuestail
(
    df.groupby(['Date','Product']).sum()
    .sort_values('Quantity')
    .groupby(level=1)
    .tail(1)
)

        Date Product  Quantity
0 2020-01-04    Beer        81
1 2020-01-03    Milk       186
2 2020-01-03  Brandy       212

我也可以得到相应的日期吗? - Keerikkattu Chellappan

3
df.groupby(['Date','Product']).sum().reset_index().groupby(
    ['Product']).max().reset_index()

输出:


    Product Date        Quantity
0   Beer    2020-01-04  151
1   Brandy  2020-01-05  72
2   Milk    2020-01-05  188

你确定对应的日期值是正确的吗? - Keerikkattu Chellappan
你的 max 覆盖了整个数据框,因此包括 DateQuantity。这有点棘手。 - Erfan

1

使用drop_duplicates检查

df.groupby(['Date','Product'],as_index=False).sum().sort_values('Quantity').drop_duplicates('Product',keep='last')
         Date Product  Quantity
11 2020-01-05    Milk       119
10 2020-01-05  Brandy       165
5  2020-01-03    Beer       302

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接