熊猫按组总和获取每个组中的最大值

时间:2020-10-07 19:04:56

标签: python pandas

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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