【问题标题】:Rounding down datetime column by the hour按小时四舍五入日期时间列
【发布时间】:2018-06-17 02:24:56
【问题描述】:
11/22/2017 10:00 14.442473
11/22/2017 10:05 19.446146
11/22/2017 10:10 49.382300
11/22/2017 10:15 51.216980
11/22/2017 10:20 50.674092
11/22/2017 10:25 14.893244
11/22/2017 10:30 27.191617
11/22/2017 10:35 19.826802
11/22/2017 10:40 9.996578
11/22/2017 10:45 7.929272
11/22/2017 10:50 22.770500
11/22/2017 10:55 32.611105
假设我有像上面这样的数据,我对所有 A 列的输出应该是:11/22/2017 10:00,因为 10:30 之后的时间被认为是 11:00,所以汇总功能将不起作用,因此需要帮助以忽略分钟和秒,以便为进一步分析做好准备。
【问题讨论】:
标签:
python
pandas
date
datetime
dataframe
【解决方案1】:
嗯,谢谢大家的回答,这是我尝试过的,效果也很好,希望它可能对某人有所帮助,因此发布..
我试过了:
df['date'] = pd.to_datetime(df['date'])
df['just_date'] = df['date'].dt.date
df['just_hour'] = df['date'].dt.hour
df['Period'] = df.just_date.astype(str).str.cat(df.just_hour.astype(str), sep=' ') + ':00:00'
【解决方案2】:
正如@cᴏʟᴅsᴘᴇᴇᴅ 所述,您需要将地址转换为datetime。
为了保留它?熊猫。我会坚持@cᴏʟᴅsᴘᴇᴇᴅ 的回答,但要这样呈现:
df.assign(Date=pd.to_datetime(df.Date).dt.floor('H'))
Date A
0 2017-11-22 10:00:00 14.442473
1 2017-11-22 10:00:00 19.446146
2 2017-11-22 10:00:00 49.382300
3 2017-11-22 10:00:00 51.216980
4 2017-11-22 10:00:00 50.674092
5 2017-11-22 10:00:00 14.893244
6 2017-11-22 10:00:00 27.191617
7 2017-11-22 10:00:00 19.826802
8 2017-11-22 10:00:00 9.996578
9 2017-11-22 10:00:00 7.929272
10 2017-11-22 10:00:00 22.770500
11 2017-11-22 10:00:00 32.611105
但是使用 Numpy 的类型的替代方法
df.assign(Date=pd.to_datetime(df.Date).values.astype('datetime64[h]'))
Date A
0 2017-11-22 10:00:00 14.442473
1 2017-11-22 10:00:00 19.446146
2 2017-11-22 10:00:00 49.382300
3 2017-11-22 10:00:00 51.216980
4 2017-11-22 10:00:00 50.674092
5 2017-11-22 10:00:00 14.893244
6 2017-11-22 10:00:00 27.191617
7 2017-11-22 10:00:00 19.826802
8 2017-11-22 10:00:00 9.996578
9 2017-11-22 10:00:00 7.929272
10 2017-11-22 10:00:00 22.770500
11 2017-11-22 10:00:00 32.611105
【解决方案3】:
从 - 开始
print(s)
11/22/2017 10:00 14.442473
11/22/2017 10:05 19.446146
11/22/2017 10:10 49.382300
11/22/2017 10:15 51.216980
11/22/2017 10:20 50.674092
11/22/2017 10:25 14.893244
11/22/2017 10:30 27.191617
11/22/2017 10:35 19.826802
11/22/2017 10:40 9.996578
11/22/2017 10:45 7.929272
11/22/2017 10:50 22.770500
11/22/2017 10:55 32.611105
Name: Data, dtype: float64
首先,使用pd.to_datetime 将索引转换为日期时间索引 -
df.index = pd.to_datetime(df.index, errors='coerce')
假设日期是此Series 的索引的一部分,请使用floor 函数以每小时频率作为日期时间 -
s.index = s.index.floor('H')
print(s)
2017-11-22 10:00:00 14.442473
2017-11-22 10:00:00 19.446146
2017-11-22 10:00:00 49.382300
2017-11-22 10:00:00 51.216980
2017-11-22 10:00:00 50.674092
2017-11-22 10:00:00 14.893244
2017-11-22 10:00:00 27.191617
2017-11-22 10:00:00 19.826802
2017-11-22 10:00:00 9.996578
2017-11-22 10:00:00 7.929272
2017-11-22 10:00:00 22.770500
2017-11-22 10:00:00 32.611105
Name: Data, dtype: float64
如果您想在数据框列上应用 floor 函数(例如,Date),请使用 .dt 访问器 -
df['Date'] = pd.to_datetime(df['Date']).dt.floor('H')