Python pandas:向包含日期的 Dataframe 列添加一小时

问题描述 投票:0回答:1

我是Python新手。
我有一个名为“日期”的 df,它存储日期。我想为整个专栏增加一个小时。

0 2011-01-07 1 2011-01-07 2 2011-01-10 3 2011-01-10 4 2011-01-10 名称:日期,长度:15644,dtype:datetime64[ns]

这是我要应用的代码

从日期时间导入日期时间,时间增量

时间戳 = pd.Timestamp('2023-01-01 12:00') new_timestamp = 时间戳 + timedelta(天=0, 小时=1)

代码本身可以正常工作,但是如何将这些函数应用到存储为 pandas 系列的 df 上?

请帮忙。 谢谢!!!

python pandas timestamp timedelta
1个回答
0
投票

据我了解,您想要给定一个充满日期的列,为每个观察添加一个小时。

使用

timedelta
lambda
功能,您可以执行以下操作:

import pandas as pd
from datetime import timedelta

dates = pd.DataFrame({'dates': ['2011-01-07', '2011-01-07', '2011-01-10', '2011-01-10', '2011-01-10']})
dates['dates'] = pd.to_datetime(dates['dates'])

# Add 1 hour to the column 
dates['dates + 1H'] = dates['dates'].apply(lambda x: x + timedelta(hours=1))

print(dates['dates +1 H'])

结果:

0   2011-01-07 01:00:00
1   2011-01-07 01:00:00
2   2011-01-10 01:00:00
3   2011-01-10 01:00:00
4   2011-01-10 01:00:00
Name: dates +1 H, dtype: datetime64[ns]
© www.soinside.com 2019 - 2024. All rights reserved.