簡體   English   中英

pandas groupby中的最大和最小日期

[英]Max and Min date in pandas groupby

我有一個看起來像這樣的數據框:

data = {'index': ['2014-06-22 10:46:00', '2014-06-24 19:52:00', '2014-06-25 17:02:00', '2014-06-25 17:55:00', '2014-07-02 11:36:00', '2014-07-06 12:40:00', '2014-07-05 12:46:00', '2014-07-27 15:12:00'],
    'type': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'C'],
    'sum_col': [1, 2, 3, 1, 1, 3, 2, 1]}
df = pd.DataFrame(data, columns=['index', 'type', 'sum_col'])
df['index'] = pd.to_datetime(df['index'])
df = df.set_index('index')
df['weekofyear'] = df.index.weekofyear
df['date'] = df.index.date
df['date'] = pd.to_datetime(df['date'])



                     type sum_col weekofyear   date
index               
2014-06-22 10:46:00    A    1       25      2014-06-22
2014-06-24 19:52:00    B    2       26      2014-06-24
2014-06-25 17:02:00    C    3       26      2014-06-25
2014-06-25 17:55:00    A    1       26      2014-06-25
2014-07-02 11:36:00    B    1       27      2014-07-02
2014-07-06 12:40:00    C    3       27      2014-07-06
2014-07-05 12:46:00    A    2       27      2014-07-05
2014-07-27 15:12:00    C    1       30      2014-07-27

我正在尋找按年分組,然后總結 sum_col。 此外,我需要找到一周中最早和最晚的日期。 第一部分非常簡單:

gb = df.groupby(['type', 'weekofyear'])
gb['sum_col'].agg({'sum_col' : np.sum})

我試圖用這個找到最小/最大日期,但沒有成功:

gb = df.groupby(['type', 'weekofyear'])
gb.agg({'sum_col' : np.sum,
        'date' : np.min,
        'date' : np.max})

如何找到出現的最早/最晚日期?

您需要組合適用於同一列的函數,如下所示:

In [116]: gb.agg({'sum_col' : np.sum,
     ...:         'date' : [np.min, np.max]})
Out[116]: 
                      date             sum_col
                      amin       amax      sum
type weekofyear                               
A    25         2014-06-22 2014-06-22        1
     26         2014-06-25 2014-06-25        1
     27         2014-07-05 2014-07-05        2
B    26         2014-06-24 2014-06-24        2
     27         2014-07-02 2014-07-02        1
C    26         2014-06-25 2014-06-25        3
     27         2014-07-06 2014-07-06        3
     30         2014-07-27 2014-07-27        1

簡單的代碼可以

df.groupby([key_field]).agg({'time_field': [np.min,np.max]})

這里的 key_field 可以是 event_id,time_field 可以是時間戳字段。

另一種可能的解決方案,您可以更好地控制生成的列名:

gb = df.groupby(['type', 'weekofyear'])
gb.agg(
    sum_col=('sum_col', np.sum),
    first_date=('date', np.min),
    last_date=('date', np.max)
).reset_index()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM