<p>您可以使用<code>apply</code>将一列添加到数据帧中,这是基于与两个日期时间数组相比的“<code>datim</code>”日期时间。这不会很好地处理大量数据,但对您来说可能没问题。例如,这将告诉您时间是否在日期时间对的<code>any</code>之间(如@Pygirl的答案):</p>
<pre><code>def between_any(time):
for s,c in zip(spacex, clonx):
if (time >= s) and (time <= c):
return True
return False
df['Between Any'] = df['datim'].apply(between_any)
</code></pre>
<p>或者,您可以获得该值所处日期对的索引:</p>
<pre><code>def between_index(time):
output = []
for i in range(len(spacex)):
if (time >= spacex[i]) and (time <= clonx[i]):
output.append(i)
return output if output else np.nan
df['Between Indices'] = df['datim'].apply(between_index)
</code></pre>
<p>或者,您可以实际获取值介于以下时间之间的时间戳:</p>
<pre><code>def between_values(time):
output = []
for s,c in zip(spacex, clonx):
if (time >= s) and (time <= c):
output.append((s,c))
return output if output else np.nan
df['Between Values'] = df['datim'].apply(between_values)
</code></pre>
<p>以下是根据您的数据得出的结果:</p>
<pre><code>In[0]: df
Out[0]:
datim
0 2019-08-14 23:26:00
1 2019-08-14 23:26:00
2 2019-08-14 23:27:00
3 2019-08-14 23:30:00
4 2019-08-14 23:30:00
5101 2020-05-25 20:48:00
5102 2020-05-25 20:49:00
5103 2020-05-26 13:52:00
5104 2020-05-26 13:52:00
5105 2020-05-26 14:22:00
In[1]:
clonx = pd.Series(['2019-08-14T23:32:00.000000000', '2019-08-14T23:35:00.000000000','2019-08-14T23:35:00.000000000','2020-05-24T14:55:00.000000000', '2020-05-24T15:03:00.000000000','2020-05-25T12:09:00.000000000'])
spacex = pd.Series(['2019-08-14T23:27:00.000000000', '2019-08-14T23:30:00.000000000','2019-08-14T23:30:00.000000000','2020-05-24T14:50:00.000000000', '2020-05-24T14:58:00.000000000','2020-05-25T12:04:00.000000000'])
clonx = pd.to_datetime(clonx)
spacex = pd.to_datetime(spacex)
df['Between Any'] = df['datim'].apply(between_any)
df['Between Indices'] = df['datim'].apply(between_index)
df['Between Values'] = df['datim'].apply(between_values)
df
Out[1]:
datim Between Any Between Indices \
0 2019-08-14 23:26:00 False NaN
1 2019-08-14 23:26:00 False NaN
2 2019-08-14 23:27:00 True [0]
3 2019-08-14 23:30:00 True [0, 1, 2]
4 2019-08-14 23:30:00 True [0, 1, 2]
5101 2020-05-25 20:48:00 False NaN
5102 2020-05-25 20:49:00 False NaN
5103 2020-05-26 13:52:00 False NaN
5104 2020-05-26 13:52:00 False NaN
5105 2020-05-26 14:22:00 False NaN
Between Values
0 NaN
1 NaN
2 [(2019-08-14 23:27:00, 2019-08-14 23:32:00)]
3 [(2019-08-14 23:27:00, 2019-08-14 23:32:00), (...
4 [(2019-08-14 23:27:00, 2019-08-14 23:32:00), (...
5101 NaN
5102 NaN
5103 NaN
5104 NaN
5105 NaN
</code></pre>