【问题标题】:How to find total time between time intervals defined by start and end columns如何查找由开始列和结束列定义的时间间隔之间的总时间
【发布时间】:2021-05-16 20:25:02
【问题描述】:

我有一个熊猫数据框:

我想通过以下方式计算确认和取消之间的差异:

对于日期 13.01.2020 和desk_id 1.0:10:35:00 - 8:00:00 + 12:36:00 - 11:36:00 + 20:00:00 - 13:36:00

我只能在确认和取消一小时的办公桌上执行这些操作。一小时是指在desk_id 的日期中,我只有一行用于确认和取消时间。当我从 8:00:00 确认和 20:00:00 减去取消时间并将它们加在一起时,我得到了有趣的差异。

有好几个小时,我无法把它放在一起。通过mamy hour,我的意思是desk_id在一个日期有几行取消和确认时间。我想选择日期、desk_id 并计算办公桌占用时间 - 每个办公桌的确认和取消之间的差异。

输出应如下所示:

我想找出一张桌子空闲的时间段。 在我的数据中可以在一个日期内进行多次确认和取消。

我做了一小时确认并取消:

df_1['confirm'] = pd.to_timedelta(df_1['confirm'].astype(str))
df_1['diff_confirm'] = df_1['confirm'].apply(lambda x: x - datetime.timedelta(days=0, hours=8, minutes=0))
df_1['cancel'] = pd.to_timedelta(df_1['cancel'].astype(str))
df_1['diff_cancel'] = df_1['cancel'].apply(lambda x: datetime.timedelta(days=0, hours=20, minutes=0)-x)

这行得通。

有什么建议吗?

【问题讨论】:

  • 感谢您纠正问题!
  • 确认和取消的“一小时”或“数小时”是什么意思?您是指confirmcancel 列中的值之间的差异吗?请添加预期输出(您希望为您提供的输入获得什么),并阐明您希望实现的计算逻辑。 “许多小时”需要执行的计算是什么?这与“一小时”的计算有何不同?
  • 感谢您的评论!我更正了,这个问题现在可以理解了吗?
  • 问题缺少一些数据。但是从你给我的东西我可以理解这些。如果我确实说错了,请纠正我,并确保在问题中也包括这些内容。 1) 工作从 08:00 开始,到 20:00 结束 2) 你想在每个 DAY 和每个 DESK ID 处计算它我真的不明白你说你的代码有效。我不太明白你想用它做什么。

标签: python pandas dataframe pandas-groupby timedelta


【解决方案1】:

您没有完全清楚您需要什么格式的结果,但我认为将它们放在单独的数据框中是可以的。因此,此解决方案对由 datedesk_id 的值定义的每组行进行操作,并计算每组的总时间,并将输出放置在新的数据帧中:

创建输入数据框的代码:

from datetime import timedelta
import pandas as pd

df = pd.DataFrame(
    {
        'date': [pd.Timestamp('2020-1-13'), pd.Timestamp('2020-1-13'),
                 pd.Timestamp('2020-1-13'), pd.Timestamp('2020-1-14'),
                 pd.Timestamp('2020-1-14'), pd.Timestamp('2020-1-14')],
        'desk_id': [1.0, 1.0, 2.0, 1.0, 2.0, 2.0],
        'confirm': ['10:36:00', '12:36:00', '09:36:00', '10:36:00', '12:36:00',
                    '15:36:00'],
        'cancel': ['11:36:00', '13:36:00', '11:36:00', '11:36:00', '14:36:00',
                   '16:36:00']
    }
)

解决方案:

df['confirm'] = pd.to_timedelta(df['confirm'])
df['cancel'] = pd.to_timedelta(df['cancel'])

# function to compute total time each desk is free
def total_time(df):
    return (
        (df.iloc[0]['confirm'] - timedelta(days=0, hours=8, minutes=0)) +
        (df['confirm'] - df['cancel'].shift()).sum() +
        (timedelta(days=0, hours=20, minutes=0) - df.iloc[-1]['cancel'])
    )

# apply function to each combination of 'desk_id' and 'date', producing
# a new dataframe
df.groupby(['desk_id', 'date']).apply(total_time).reset_index(name='total_time')


#    desk_id          date       total_time
# 0      1.0    2020-01-13  0 days 10:00:00
# 1      1.0    2020-01-14  0 days 11:00:00
# 2      2.0    2020-01-13  0 days 10:00:00
# 3      2.0    2020-01-14  0 days 09:00:00

该函数取confirm 的第一个值和8:00:00 之间的差值,取每个confirm 和前面cancel 值之间的差值,然后是20:00:00 和最后一个值之间的差值cancel 的值。这些差异加在一起产生最终值。

【讨论】:

    【解决方案2】:

    猜测你想要做什么(我仍然不能完全理解,但这是一个尝试):

    import pandas as pd
    from datetime import timedelta as td
    #create the dataframe
    a = pd.DataFrame({'data':['2020-01-13','2020-01-13','2020-01-14'],'desk_id':[1.0,1.0,1.0],'confirm':['10:36:00','12:36:00','13:14:00'],'cancel':['11:36:00','13:36:00','13:44:00']})
    
    def get_avail_times(df,start_end_delta=td(hours=12)):
        df['confirm'] = pd.to_timedelta(df['confirm'])
        df['cancel'] = pd.to_timedelta(df['cancel'])
        #group by the two keys so that we can perform calculations on the specific groups!!
        df_g = df.groupby(['data','desk_id'], as_index=False).sum()
        df_g['total_time'] = start_end_delta - df_g['cancel'] + df_g['confirm'] 
        return df_g.drop('confirm',1).drop('cancel',1)
    
    output = get_avail_times(a)
    

    它给出了输出:

             data  desk_id      total_time
    0  2020-01-13      1.0 0 days 10:00:00
    1  2020-01-14      1.0 0 days 11:30:00
    

    这里的关键是使用 .groupby() 函数,然后我们可以将其相加以基本上执行方程:

    total_time = 20:00 + sum_confirm_times - sum_cancel_times - 08:00

    【讨论】:

    • 如果这个答案解决了你的问题,请选择或批准,谢谢:)
    猜你喜欢
    • 2013-01-11
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多