将小时列转换为日期时间失败

Convert Hour column to datetime failes

我在 pandas 中有以下 table:

>>>TIMESTAMP                date         Hour         patient1     patient2    patient3   patient4 ....
0  2019-06-13 12:00:00     2019-06-13   12:00:00      -0.456       -0.124      -0.451     -2.257
1  2019-06-13 12:03:00     2019-06-13   12:03:00      -0.456       -0.134      -0.781     -2.357
2  2019-06-13 12:06:00     2019-06-13   12:06:00      -0.876       -0.238      -0.983     -1.824
...
   2019-07-04 22:03:00     2019-07-04   12:03:00      -0.568       -0.532      -0.451      0.789
n  2019-07-04 22:06:00     2019-07-04   12:06:00      -0.021       -0.981      -0.293      1.824

我有时间戳列,它是日期时间,我有从 TIMESTAMP 列中拆分出来的日期和小时列,如下所示:

# #two cOlumns for hour and for date
df['Date'] = [d.date() for d in df['Timestamp']]
df['Hour'] = [d.time() for d in df['Timestamp']]

问题是我只想从我的数据库中 select 2019-06-20 到 2019-07-02 之间的行,并且小时将在 07:00 到 17:00。由于日期时间格式的问题,这不起作用。

我尝试使用 between:


df=df[(df['date'].between('2019-06-20','2019-07-02'))&(df['Hour'].between('07:00','17:00'))]

但后来我得到了这个错误:

TypeError: '>=' not supported between instances of 'datetime.date' and 'str'

所以我检查了数据类型,发现日期和小时是对象类型,所以我尝试像这样更改它们的类型:

df['date'] = pd.to_datetime(df['date']).dt.date
df['Hour'] = pd.to_datetime(df['Hour']).dt.time

但出现错误:

TypeError: <class 'datetime.time'> is not convertible to datetime

我的最终目标是能够 select 只有在我想要的日期和时间范围内的行(2019-06-20 到 2019-07-02 和小时将在 07:00 到 17:00 之间。

您最好将时间和日期更改为以下格式的数字(int): 日期至 -> YYYYMMDD 时间 -> HHMM

通过以下代码:

df['time'] = df['Timestamp'].dt.strftime('%H%M').astype(int)
df['date'] = df['Timestamp'].dt.strftime('%Y%m%d').astype(int)

然后你可以很容易地与整数进行比较:

df=df[(df['date'].between(20190620,20190702))&(df['Hour'].between(700,1700))]

使用 Series.dt.floor 代替删除时间 date 并使用 time 构造函数:

print (df)
                           date      Hour  patient1  patient2  patient3
TIMESTAMP                                                              
2019-06-13 12:00:00  2019-06-25  12:00:00    -0.456    -0.124    -0.451 <-date for match
2019-06-13 12:03:00  2019-06-13  12:03:00    -0.456    -0.134    -0.781
2019-06-13 12:06:00  2019-06-13  12:06:00    -0.876    -0.238    -0.983
2019-07-04 22:03:00  2019-07-04  12:03:00    -0.568    -0.532    -0.451
2019-07-04 22:06:00  2019-07-04  12:06:00    -0.021    -0.981    -0.293

from datetime import time

df['date'] = pd.to_datetime(df['date']).dt.floor('d')
#it looks already time column, so should be removed
#df['Hour'] = pd.to_datetime(df['Hour'].astype(str)).dt.time

df=df[(df['date'].between('2019-06-20','2019-07-02')&
       df['Hour'].between(time(7,0,0),time(17,0,0)))]

print (df)
                          date      Hour  patient1  patient2  patient3
TIMESTAMP                                                             
2019-06-13 12:00:00 2019-06-25  12:00:00    -0.456    -0.124    -0.451