【问题标题】:How to calculate the time difference (date and time are in the same column) and put this difference in a separate column?如何计算时差(日期和时间在同一列中)并将此差异放在单独的列中?
【发布时间】:2021-11-11 03:18:02
【问题描述】:

遇到了问题。有一个数据框,我需要在其中计算每个用户的操作之间经过了多少时间,并在此表的单独列中指出这种差异。原来是用DateTime单独计算时间,但是在表中怎么做呢?

table = pd.DataFrame({
    'user': ['Steve', 'Steve', 'Steve', 'Jack', 'Jack', 'Jack'],
    'country':['UK', 'UK', 'UK', 'CH', 'CH', 'CH'],
    'date': ['2018-01-15 00:05:07', '2018-01-15 00:06:14', '2018-01-15 00:08:36',
             '2018-01-15 00:14:51', '2018-01-15 00:15:18', '2018-01-15 00:17:24']
})
table.set_index('country', inplace=True)

for i in table.groupby(['country', 'user']):
    print(i)

在单独的列中,您应该得到:

给杰克

  1. 00:14:51
  2. 00:00:27
  3. 00:02:06

给史蒂夫

  1. 00:05:07
  2. 00:01:07
  3. 00:02:22

【问题讨论】:

    标签: python pandas dataframe datetime pandas-groupby


    【解决方案1】:

    使用DataFrameGroupBy.diff 表示每组的差异 - 输出是时间增量:

    table['date'] = pd.to_datetime(table['date'])
    
    s = pd.to_timedelta(table['date'].dt.strftime('%H:%M:%S'))
    table['new'] = table.groupby(['country', 'user'])['date'].diff().fillna(s)
    
    print (table)
              user                date             new
    country                                           
    UK       Steve 2018-01-15 00:05:07 0 days 00:05:07
    UK       Steve 2018-01-15 00:06:14 0 days 00:01:07
    UK       Steve 2018-01-15 00:08:36 0 days 00:02:22
    CH        Jack 2018-01-15 00:14:51 0 days 00:14:51
    CH        Jack 2018-01-15 00:15:18 0 days 00:00:27
    CH        Jack 2018-01-15 00:17:24 0 days 00:02:06
    

    如果需要将时间增量转换为字符串:

    def format_timedelta(x):
        ts = x.total_seconds()
        hours, remainder = divmod(ts, 3600)
        minutes, seconds = divmod(remainder, 60)
        return ('{:02d}:{:02d}:{:02d}').format(int(hours), int(minutes), int(seconds)) 
    
    table['new'] = table['new'].apply(format_timedelta)
    
    print (table)
              user                date       new
    country                                     
    UK       Steve 2018-01-15 00:05:07  00:05:07
    UK       Steve 2018-01-15 00:06:14  00:01:07
    UK       Steve 2018-01-15 00:08:36  00:02:22
    CH        Jack 2018-01-15 00:14:51  00:14:51
    CH        Jack 2018-01-15 00:15:18  00:00:27
    CH        Jack 2018-01-15 00:17:24  00:02:06
    

    我认为0 每组的第一个值更好:

    table['date'] = pd.to_datetime(table['date'])
    
    table['new'] = table.groupby(['country', 'user'])['date'].diff().fillna(pd.Timedelta(0))
    
    print (table)
              user                date             new
    country                                           
    UK       Steve 2018-01-15 00:05:07 0 days 00:00:00
    UK       Steve 2018-01-15 00:06:14 0 days 00:01:07
    UK       Steve 2018-01-15 00:08:36 0 days 00:02:22
    CH        Jack 2018-01-15 00:14:51 0 days 00:00:00
    CH        Jack 2018-01-15 00:15:18 0 days 00:00:27
    CH        Jack 2018-01-15 00:17:24 0 days 00:02:06
    

    【讨论】:

    • 我在这里发布了部分数据框。但是,当我在 Jupiter 的笔记本中使用您的解决方案时,在完整的数据帧上,它不会加载。只显示“*”
    • @RinatDevyatyarov - 你能检查一下this 吗?
    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多