【问题标题】:Add hours to timestamps in a pandas df在 pandas df 中为时间戳添加小时数
【发布时间】:2018-08-16 23:31:45
【问题描述】:

我正在尝试将 hours 添加到 pandas df 中的特定值,以便它们保持一致。

对于下面的df,我想将24 hours 添加到第一个值。

import pandas as pd

d = ({
    'time' : ['3:00:00','27:30:00','28:00:00'],               
     })

df = pd.DataFrame(data=d)

我现在正在使用它。

df['time'].iloc[0] = df['time'].iloc[0] + pd.Timedelta(hours=24)

但它会产生:

              time
0  1 days 03:00:00
1         27:30:00
2         28:00:00

我的预期输出是:

              time
0         27:00:00
1         27:30:00
2         28:00:00

【问题讨论】:

标签: python pandas time


【解决方案1】:

首先这不是时间增量,如果你在输出后执行df.applymap(type),你会看到第一个是时间对象,其他的应该是str。

我只能在脑海中浮现这个

df1=df.time.str.split(':',expand=True)
df1.iloc[0,0]=str(int(df1.iloc[0,0])+24)
df1
Out[63]: 
    0   1   2
0  27  00  00
1  27  30  00
2  28  00  00
df1.apply(':'.join,1)# you can add `to_frame('Time') ` as the end 
Out[64]: 
0    27:00:00
1    27:30:00
2    28:00:00
dtype: object

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2011-01-31
    • 2020-02-04
    • 2018-04-29
    • 1970-01-01
    • 2015-01-25
    相关资源
    最近更新 更多