【问题标题】:How to Aggregate and Sum in Python (or R) with a Specific Condition如何在具有特定条件的 Python(或 R)中进行聚合和求和
【发布时间】:2020-06-15 06:43:22
【问题描述】:

目标

我有一个数据集 df,我想对长度列进行分组,取其总和,并显示与之关联的结束时间:

 length start                      end                      duration
 6330   12/17/2019 10:34:23 AM     12/17/2019 10:34:31 AM   8
 57770  12/19/2019 5:19:56 PM      12/17/2019 5:24:19 PM    263
 6330   12/17/2019 10:34:54 AM     12/17/2019 10:35:00 AM   6
 6330   12/18/2019 4:36:44 PM      12/18/2019 4:37:13 PM    29
 57770  12/19/2019 5:24:47 PM      12/19/2019 5:26:44 PM    117

期望的输出

length  end                     total Duration
6330    12/18/2019 4:37:13 PM   43  
57770   12/19/2019 5:26:44 PM   380 

输出

structure(list(length = c(6330L, 57770L, 6330L, 6330L, 57770L
), start = structure(c(1L, 4L, 2L, 3L, 5L), .Label = c("12/17/2019 10:34:23 AM", 
"12/17/2019 10:34:54 AM", "12/18/2019 4:36:44 PM", "12/19/2019 5:19:56 PM", 
"12/19/2019 5:24:47 PM"), class = "factor"), end = structure(c(1L, 
3L, 2L, 4L, 5L), .Label = c("12/17/2019 10:34:31 AM", "12/17/2019 10:35:00 AM", 
"12/17/2019 5:24:19 PM", "12/18/2019 4:37:13 PM", "12/19/2019 5:26:44 PM"
), class = "factor"), duration = c(8L, 263L, 6L, 29L, 117L)), class = "data.frame", row.names =    c(NA, 
-5L))

这是我尝试过的:但我如何也显示与“最新”长度值相关联的结束列? 例如,长度 6330 有 3 个结束值,并附加了 3 个持续时间:

           12/17/2019 10:34:31 AM            8
           12/17/2019 10:35:00 AM            6
           12/18/2019 4:37:13 PM            29


12/18/2019 4:37:13 PM is the latest end time, so I would like to output the end time, 
along with the sum of durations for this particular length value. 

期望的输出

length  end                     total Duration
6330    12/18/2019 4:37:13 PM   43  
57770   12/19/2019 5:26:44 PM   380 

这是我尝试过的:

import pandas as pd
import numpy as np

df1 = df.groupby('length')['duration'].sum()

但是,它只输出长度和总持续时间。我将如何输出长度,最新结束 以及该特定长度的总持续时间?

感谢任何帮助。

【问题讨论】:

  • 我敢肯定有一百万个关于这样的事情的答案,但基本上:df.groupby('length').agg({'duration' : 'sum', 'end' : 'max'}).reset_index()。如果你愿意,你可以做.agg({'end' : ['max','min']}) 等等等等。几乎无限的可能性。
  • 哦,我看到@elPastor 我仍在学习 Python 知识。我得试试这个。谢谢
  • 是的,这是一个非常具体的 pandas 函数(相对于纯 python),但我希望它有所帮助。
  • 我现在正在尝试这个。我希望如此谢谢你
  • 这行得通@elPastor——也许你可以把它作为答案发布,因为它行得通,谢谢

标签: python r pandas numpy dplyr


【解决方案1】:

在R中,我们可以按'length'分组,使用summarise得到'duration'的sum,并用mdy_hms转换为DateTime类后提取'end'的max元素(来自lubridate)

library(dplyr)
library(lubridate)
df %>%
   group_by(length) %>% 
   summarise(duration = sum(duration), end = end[which.max(mdy_hms(end))])

【讨论】:

    【解决方案2】:

    我们可以使用 GroupBy.agg 来处理 Pandas,但这里我们有两个选择:

    1. 简单的字典聚合:
    df.groupby('length').agg({'duration': 'sum', 'end': 'max'}).reset_index()
    
       length  duration                 end
    0    6330        43 2019-12-18 16:37:13
    1   57770       380 2019-12-19 17:26:44
    

    1. Named aggregations,在聚合时重命名列:

    pandas 0.25.0+之后的新功能

    df.groupby('length').agg(
        end=('end', 'max'),
        total_duration=('duration', 'sum')
    ).reset_index()
    
       length                 end  total_duration
    0    6330 2019-12-18 16:37:13              43
    1   57770 2019-12-19 17:26:44             380
    

    注意:不要忘记将您的日期列转换为日期时间之前:

    df[['start', 'end']] = (
        df[['start', 'end']].apply(lambda x: pd.to_datetime(x, infer_datetime_format=True))
    )
    

    【讨论】:

    • infer_datetime_format = True in pd.to_datetime() 用于在大型数据集的情况下大幅提高速度。
    【解决方案3】:

    在 R 中,可以使用一些 tidyverse 库来完成:

    library(tidyverse)
    
    df <- tribble(
    ~length,~start,~end,~duration,
    6330,"12/17/2019 10:34:23 AM","12/17/2019 10:34:31 AM",8,
    57770,"12/19/2019 5:19:56 PM","12/17/2019 5:24:19 PM",263,
    6330,"12/17/2019 10:34:54 AM","12/17/2019 10:35:00 AM",6,
    6330,"12/18/2019 4:36:44 PM","12/18/2019 4:37:13 PM",29,
    57770,"12/19/2019 5:24:47 PM","12/19/2019 5:26:44 PM",117
    ) %>% 
      mutate_at(
        vars(start, end),
        lubridate::mdy_hms
      )
    
    df %>% 
      group_by(length) %>% 
      summarise(
        end = max(end, na.rm = TRUE),
        duration = sum(duration, na.rm = TRUE)
      )
    

    给予:

    # A tibble: 2 x 3
      length end                 duration
       <dbl> <dttm>                 <dbl>
    1   6330 2019-12-18 16:37:13       43
    2  57770 2019-12-19 17:26:44      380
    

    时间戳以 ISO 格式格式化。

    我在转换值时使用了默认的 TZ (UTC)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-25
      • 2012-03-12
      • 1970-01-01
      • 2019-03-05
      • 2021-11-04
      • 1970-01-01
      • 2020-07-01
      • 2019-04-13
      相关资源
      最近更新 更多