Pandas间隔时间布尔值

2024-04-20 01:47:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个列,如果行值在09:00到17:00之间,则该列将赋值为true。在

我可以使用between_time很容易地选择这些时间,但是不能分配一个新列a TrueFalse。在

df = df.between_time('9:00', '17:00', include_start=True, include_end=True)

此语句选择适当的行,但不能为它们指定True False值。在

我一直在尝试使用np.where。在

^{pr2}$

只是np.where只对布尔表达式有效。在

我是这样用的:

df['day'] = np.where((df['dayTime'] < '09:00') & (df['dayTime'] > '17:00'),'True','False')

但只得到False returns,因为一个值不能同时大于17小于9。在

我错过了一个相对容易的步骤,我想不通。救命啊。在


Tags: falsetruedfincludetimenp时间between
1条回答
网友
1楼 · 发布于 2024-04-20 01:47:56

您可以执行以下操作:

df.index.isin(df.between_time('9:00', '17:00', include_start=True, include_end=True).index)

因为between方法返回一个dataframe,而不是一个我们可以像对任何dataframe一样调用.index的布尔数组,因此它将返回一系列的时间。然后我们可以检查原始时间索引是否包含在由between方法得到的时间索引中。在

这将为您提供一个时间范围内的布尔值数组。我想不出别的办法了,但这并不意味着就没有办法了

相关问题 更多 >