【问题标题】:How to calculate day count from dates in different rows (Time in state calculation)如何根据不同行中的日期计算天数(状态计算时间)
【发布时间】:2020-08-13 19:26:23
【问题描述】:

假设我有一个如下所示的数据框:

Event           Transition Date        From             To  
ESS-123     2018-12-28 10:27:35.913  Planning       In Progress
ESS-123     2019-04-20 10:51:07.857  In Progress    Deferred
HTO-254     2019-04-04 15:19:06.013  Planning       In Progress
HTO-254     2019-05-05 10:35:03.083  In Progress    Not in work
HTO-254     2019-05-24 10:55:12.280  Work Planned   In Progress
AEW-8465    2018-10-01 09:40:34.070  Work Planned   In Progress
AEW-8465    2018-10-01 10:30:07.993  In Progress    Suspended
AEW-8465    2018-10-25 12:22:13.203  Drafted        In Progress
AEW-8465    2019-02-05 15:58:13.900  In Progress    Suspended

我希望能够计算每个事件的“进行中”状态的时间。所以我必须能够按事件过滤,聚合状态时间,并将其添加到新列中。我什至不知道从哪里开始。任何人的任何帮助都将不胜感激。

【问题讨论】:

  • 看看groupbyshift。此问题中的示例stackoverflow.com/questions/53335567/…
  • 这正是我需要的,还有一个面具来完成这项工作。下面的答案使用了相同的方法。感谢您的帮助!

标签: python pandas numpy


【解决方案1】:

只需计算每一行的差异,然后根据需要进行过滤...这假设您的框架已正确排序

# create groupby object
g = df.groupby('Event')
# calculate the difference for each group
df['diff'] = g['Transition Date'].diff(periods=1)
# create a mask to filter based on your conditions
mask = ((g['To'].shift(0) == 'In Progress') & (g['From'].shift(-1) == 'In Progress')) |\
       ((g['From'].shift(0) == 'In Progress') & (g['To'].shift(1) == 'In Progress'))
print(df[mask])

      Event         Transition Date          From           To  \
0   ESS-123 2018-12-28 10:27:35.913      Planning  In Progress   
1   ESS-123 2019-04-20 10:51:07.857   In Progress     Deferred   
2   HTO-254 2019-04-04 15:19:06.013      Planning  In Progress   
3   HTO-254 2019-05-05 10:35:03.083   In Progress  Not in work   
5  AEW-8465 2018-10-01 09:40:34.070  Work Planned  In Progress   
6  AEW-8465 2018-10-01 10:30:07.993   In Progress    Suspended   
7  AEW-8465 2018-10-25 12:22:13.203       Drafted  In Progress   
8  AEW-8465 2019-02-05 15:58:13.900   In Progress    Suspended   

                      diff  
0                      NaT  
1 113 days 00:23:31.944000  
2                      NaT  
3  30 days 19:15:57.070000  
5                      NaT  
6   0 days 00:49:33.923000  
7  24 days 01:52:05.210000  
8 103 days 03:36:00.697000  

或者如果您想要每个事件进行中花费的总时间

df[mask].groupby('Event')['diff'].sum()

Event
AEW-8465   127 days 06:17:39.830000
ESS-123    113 days 00:23:31.944000
HTO-254     30 days 19:15:57.070000
Name: diff, dtype: timedelta64[ns]

【讨论】:

  • 这正是我所需要的!太感谢了!我什至没有想过要戴口罩。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 2021-12-31
相关资源
最近更新 更多