答案 0 :(得分:1)
您应在此处使用shift
s=df['datetime_column'].ffill()
df['datetime_column_x']=np.where(df.datetime_column.dt.hour.between(0,9),s.shift(),df['datetime_column'])
df
Out[441]:
datetime_column datetime_column_x
0 2018-09-19 17:00:03 2018-09-19 17:00:03
1 NaT NaT
2 NaT NaT
3 NaT NaT
4 2018-09-20 07:00:30 2018-09-19 17:00:03
5 NaT NaT
6 NaT NaT
7 NaT NaT
8 2018-09-21 13:00:30 2018-09-21 13:00:30
9 NaT NaT
10 NaT NaT
11 NaT NaT
12 NaT NaT
13 2018-09-22 20:00:30 2018-09-22 20:00:30
14 NaT NaT
15 NaT NaT
16 NaT NaT
17 NaT NaT
18 2018-09-22 04:00:30 2018-09-22 20:00:30
答案 1 :(得分:0)
Wen-Ben的答案很全面-但请确保您的日期格式正确,可与python的datetime
库进行比较。这不适用于numpy datetime64
对象。
将日期转换为datetime
或大熊猫Timestamp
对象:
df['datetime'] = pd.to_datetime(df.loc[:, 'datetime'])
# or
df['datetime'] = df.loc[:, 'datetime'].apply(pd.Timestamp)
然后像文本所说的那样,比较datetime.time
属性。