【问题标题】:Handle different time formats in a dataframe处理数据框中的不同时间格式
【发布时间】:2020-03-05 23:50:20
【问题描述】:

我正在处理一个数据框,其中有一列重新组合了不同的时间格式,例如

    Time                ID    ...
0   1 hrs 1 min 1 sec   1     
1   1 min 1 sec         2
2   1 sec               1

我想计算按 id 分组的时间列的平均值。 我的问题是时间格式取决于行。

我尝试在时间列上使用mean() 函数

df[["ID", "Time"]].groupby(["ID"]).agg(lambda x: x.mean())

但它不起作用。 我试图格式化日期然后计算平均值,但是 format="%H hrs %M min %S sec" 仅适用于第一种情况,我得到一个错误:

ValueError: 时间数据 '1 min 1 sec' 与格式 '%H hrs %M min %S sec' 不匹配(搜索)

【问题讨论】:

    标签: python-3.x pandas dataframe time


    【解决方案1】:

    Time 转换为Timedelta 并转换为秒并调用mean。在此之前,您需要将hrs 替换为hours

    s = pd.to_timedelta(df.Time.replace('hrs', 'hours', regex=True)).dt.total_seconds()
    s.groupby(df.ID).mean()
    
    Out[110]:
    ID
    1    1831.0
    2      61.0
    Name: Time, dtype: float64
    

    【讨论】:

    • 谢谢!我将“hrs”替换为“hours”,转换为TimeDelta,可以直接调用mean()函数!
    • 不客气。使用apply 没有任何问题。我从apply 更改为直接使用pd.to_timedelta 以使其更快。如果您仍想使用apply,请告知您
    猜你喜欢
    • 2013-09-01
    • 2021-12-26
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2021-11-12
    • 2015-02-22
    相关资源
    最近更新 更多