【问题标题】:Subtract time value to column of times in Pandas将时间值减去 Pandas 中的时间列
【发布时间】:2018-03-24 08:42:51
【问题描述】:

我有一列这样的时间

df = pd.DataFrame({'times':['10:59:20.1647', '11:05:46.2258', '11:10:59.4658']})

我的目标是第一次减去所有这些时间。为此,我将列转换为datetime.time 类型并将第一个值减去所有列:

pd.to_datetime(df['times']).dt.time - pd.to_datetime(df['times']).dt.time.iloc[0]

但是,这样做我得到一个错误:

TypeError: unsupported operand type(s) for -: 'datetime.time' and'datetime.time'

您能否建议一种聪明而优雅的方式来实现我的目标?

【问题讨论】:

    标签: pandas datetime dataframe time subtraction


    【解决方案1】:

    使用timedeltas:

    a = pd.to_timedelta(df['times'])
    b =  a - a.iat[0]
    print (b)
    0          00:00:00
    1   00:06:26.061100
    2   00:11:39.301100
    Name: times, dtype: timedelta64[ns]
    

    如果需要的话:

    c = pd.to_datetime(b).dt.time
    print (c)
    0           00:00:00
    1    00:06:26.061100
    2    00:11:39.301100
    Name: times, dtype: object
    
    print (c.apply(type))
    0    <class 'datetime.time'>
    1    <class 'datetime.time'>
    2    <class 'datetime.time'>
    Name: times, dtype: object
    

    输出timedelta的另一种解决方案:

    a = pd.to_datetime(df['times'])
    b =  a - a.iat[0]
    print (b)
    0          00:00:00
    1   00:06:26.061100
    2   00:11:39.301100
    Name: times, dtype: timedelta64[ns]
    

    【讨论】:

    • 最后一件事:假设我想根据小数四舍五入秒我该怎么办?在此先感谢:)
    • 那么00:06:26.061100 的期望输出是什么?
    • 00:06:26.061100 将是 00:06:26 / 00:06:28.510000 将是 00:06:28
    • 您可以使用print (b.dt.round('S')),但它与您的想法有些不同——请查看this 以获得解释。
    猜你喜欢
    • 2022-07-07
    • 1970-01-01
    • 2021-03-17
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多