检查Pandas datetime列是否在某个时间范围内
Check whether Pandas datetime column is within a certain time range
我有一个 Pandas 数据框,其“日期时间”列包含一个日期时间:)
ColA Datetime ColB
---- ------------------- ----
1 2021-01-01 05:02:22 SomeVal
2 2021-01-01 01:01:22 SomeOtherVal
我想创建一个只有两个规则的新日期列:
1. If the "time" element of datetime is between 00:00:00 and 02:00:00 then make Date the "date" element of Datetime - 1 (the previous day)
2. Otherwise make Date the "date" element of Datetime as is
为此,我将不得不 运行 检查日期时间列。那看起来怎么样?另外,如果我不需要迭代数据框来实现这一点,可以加分。
将值转换为日期时间,如果时间不太像 02:00:00
在 Series.mask
中减去一天:
from datetime import time
df['Datetime'] = pd.to_datetime(df['Datetime'])
df['Datetime'] = df['Datetime'].mask(df['Datetime'].dt.time <= time(2, 0, 0),
df['Datetime'] - pd.Timedelta('1 day'))
print (df)
ColA Datetime ColB
0 1 2021-01-01 05:02:22 SomeVal
1 2 2020-12-31 01:01:22 SomeOtherVal
我有一个 Pandas 数据框,其“日期时间”列包含一个日期时间:)
ColA Datetime ColB
---- ------------------- ----
1 2021-01-01 05:02:22 SomeVal
2 2021-01-01 01:01:22 SomeOtherVal
我想创建一个只有两个规则的新日期列:
1. If the "time" element of datetime is between 00:00:00 and 02:00:00 then make Date the "date" element of Datetime - 1 (the previous day)
2. Otherwise make Date the "date" element of Datetime as is
为此,我将不得不 运行 检查日期时间列。那看起来怎么样?另外,如果我不需要迭代数据框来实现这一点,可以加分。
将值转换为日期时间,如果时间不太像 02:00:00
在 Series.mask
中减去一天:
from datetime import time
df['Datetime'] = pd.to_datetime(df['Datetime'])
df['Datetime'] = df['Datetime'].mask(df['Datetime'].dt.time <= time(2, 0, 0),
df['Datetime'] - pd.Timedelta('1 day'))
print (df)
ColA Datetime ColB
0 1 2021-01-01 05:02:22 SomeVal
1 2 2020-12-31 01:01:22 SomeOtherVal