当在几秒钟内获得大量数字以达到平均值、最大值和最小值时,如何转换为日期时间格式?

How do I convert to a datetime format when getting huge numbers in seconds to reach mean, max and min?

我使用以下 python 命令,得到的结果我不知道如何转换为小时或任何其他时间标准。我的目标是了解两个学生组登录行为的平均值、最小值和最大值,并计算每个组中每个学生的所有登录次数,直到截止日期。

数据 (col2) - 从学生结束大学注册的日期减去每个学生的不同登录时间的结果(col2 中带负号的数字表示截止日期后没有登录):

        User Name      status  Col1  ...       Col2               Check Check all
4053       191446  terminated  Diploming  ...  -62 days +00:31:00     0         0
4054       191446  terminated  Diploming  ...  -62 days +00:23:00     0         0
4055       191446  terminated  Diploming  ...  -62 days +00:20:00     0         0
55838      190690  terminated  Diploming  ... -142 days +21:17:00     0         0
55839      190690  terminated  Diploming  ... -142 days +15:10:00     0         0
...           ...         ...        ...  ...                 ...   ...       ...
464817     194056  terminated   Bachelor  ... -103 days +05:19:00     0         0
466349     193858  terminated   Bachelor  ... -103 days +20:23:00     0         0
467668     194060  terminated   Bachelor  ... -153 days +09:59:00     0         0
468590     194018  terminated   Bachelor  ... -154 days +23:07:00     0         0
469805     175440  terminated   Bachelor  ... -154 days +13:38:00     0         0

这是我正在使用的代码

result = result.groupby('col1').agg({'col2': ['mean', 'min', 'max']})

print("\nMean, min, and max values of student line logons - indifinite")
print(result)

print("\nresult.columns")
print(result.columns)

这是我得到的结果

Mean, min, and max values of student line logons
               time_diff                            
                    mean           min           max
Col1                                          
Bachelor   -8.089769e+12 -1.872721e+13 -3.622951e+10
Diploming  -8.718830e+12 -1.586661e+13 -1.426230e+10

我怎样才能从 'Mean, min, and max values of student line logons' 中得到有意义的结果,可能会像上面 'Data (col2)' 中的 col2 那样呈现结果?感谢您提供任何明智的意见...;o) 谢谢。

使用 Series.dt.total_seconds 将 timedeltas 转换为秒,聚合并在必要时将秒转换回 timedeltas:

result['Col2'] = result['Col2'].dt.total_seconds()
result = (result.groupby('Col1')['Col2'].agg(['mean', 'min', 'max'])
                .apply(pd.to_timedelta, unit='s'))
print (result)
                         mean                 min                 max
Col1                                                                 
Bachelor  -133 days +04:53:12 -154 days +13:38:00 -103 days +20:23:00
Diploming  -94 days +07:32:12 -142 days +15:10:00  -62 days +00:31:00

编辑:绘图最好使用:

result['Col2'] = result['Col2'].dt.total_seconds()
result1 = result.groupby('Col1')['Col2'].agg(['mean', 'min', 'max'])

如果想通过 0 替换缺失值来避免错误,请使用:

result['Col2'] = result['Col2'].dt.total_seconds()
result2 = (result.groupby('Col1')['Col2'].agg(['mean', 'min', 'max'])
                .apply(pd.to_timedelta, unit='s')
                .fillna(pd.Timedelta(0))