从Pandas数据框列中删除"秒"和"分钟"

Dus*_*ell 5 python time-series dataframe pandas

给定一个数据帧,如:

import numpy as np
import pandas as pd

df = pd.DataFrame(
{'Date' : pd.date_range('1/1/2011', periods=5, freq='3675S'),
 'Num' : np.random.rand(5)})
                 Date       Num
0 2011-01-01 00:00:00  0.580997
1 2011-01-01 01:01:15  0.407332
2 2011-01-01 02:02:30  0.786035
3 2011-01-01 03:03:45  0.821792
4 2011-01-01 04:05:00  0.807869
Run Code Online (Sandbox Code Playgroud)

我想删除'分钟'和'秒'信息.

以下(主要是从以下方面偷来的:如何删除Pandas数据帧索引的'秒')工作正常,

df = df.assign(Date = lambda x: pd.to_datetime(x['Date'].dt.strftime('%Y-%m-%d %H')))
                 Date       Num
0 2011-01-01 00:00:00  0.580997
1 2011-01-01 01:00:00  0.407332
2 2011-01-01 02:00:00  0.786035
3 2011-01-01 03:00:00  0.821792
4 2011-01-01 04:00:00  0.807869
Run Code Online (Sandbox Code Playgroud)

但是将日期时间转换为字符串然后再转换为日期时间会感觉很奇怪.有没有办法更直接地做到这一点?

piR*_*red 8

dt.round

这是应该怎么做...使用 dt.round

df.assign(Date=df.Date.dt.round('H'))

                 Date       Num
0 2011-01-01 00:00:00  0.577957
1 2011-01-01 01:00:00  0.995748
2 2011-01-01 02:00:00  0.864013
3 2011-01-01 03:00:00  0.468762
4 2011-01-01 04:00:00  0.866827
Run Code Online (Sandbox Code Playgroud)

老答复

一种方法是设置索引和使用 resample

df.set_index('Date').resample('H').last().reset_index()

                 Date       Num
0 2011-01-01 00:00:00  0.577957
1 2011-01-01 01:00:00  0.995748
2 2011-01-01 02:00:00  0.864013
3 2011-01-01 03:00:00  0.468762
4 2011-01-01 04:00:00  0.866827
Run Code Online (Sandbox Code Playgroud)

另一种选择是剥离datehour组件

df.assign(
    Date=pd.to_datetime(df.Date.dt.date) +
         pd.to_timedelta(df.Date.dt.hour, unit='H'))

                 Date       Num
0 2011-01-01 00:00:00  0.577957
1 2011-01-01 01:00:00  0.995748
2 2011-01-01 02:00:00  0.864013
3 2011-01-01 03:00:00  0.468762
4 2011-01-01 04:00:00  0.866827
Run Code Online (Sandbox Code Playgroud)

  • 注意:2030-01-01 21:54:00 的回合是 2030-01-01 22:00:00 而不是 2030-01-01 21:00:00 --- 为此使用 dt.floor (3认同)