[英]loop through python datetimes in specified range TypeError
I want to create a scatter plot for every 10 minutes in the time period specified by t_list
.我想在 t_list 指定的时间段内每 10 分钟创建一个散点图
t_list
。 I get the error TypeError: cannot compare a dtyped [datetime64[ns]] array with a scalar of type [bool]
in the line df_t = df[(df['datetime']>=t & df['datetime']<t_end)]
but the type for t
and t_end
are both datetime
.我收到错误
TypeError: cannot compare a dtyped [datetime64[ns]] array with a scalar of type [bool]
df_t = df[(df['datetime']>=t & df['datetime']<t_end)]
但t
和t_end
的类型都是datetime
。 non of the variables are type bool
.非变量是
bool
类型。
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
df_data = pd.read_csv('C:\SCADA.csv')#import data
#format Timestamp as datetime
df_data['datetime'] = pd.to_datetime(df_data['TimeStamp'] )
#create df of time period
df = df_data[(df_data['datetime']>= datetime(2017, 12, 23, 06,00, 00)) &
(df_data['datetime']< datetime(2017, 12, 23, 07, 00, 00))]
#time period I want to create 10 min plots for
t_list = [datetime(2017, 12, 23, 06, 00, 00), datetime(2017, 12, 23, 07, 00, 00)]
for t in t_list:
t_end = t + timedelta(minutes = 10)
#breaks here with
TypeError: cannot compare a dtyped [datetime64[ns]] array with a
scalar of type [bool]
df_t = df[(df['datetime']>=t & df['datetime']<t_end)]
#code continues with plotting scatter plots within the loop
When boolean indexing with multiple conditions, you should wrap each single condition in brackets.当 boolean 索引具有多个条件时,您应该将每个单个条件括在括号中。
From the docs:从文档:
Another common operation is the use of boolean vectors to filter the data.
另一种常见的操作是使用 boolean 向量来过滤数据。 The operators are: |
运算符是: | for or, & for and, and ~ for not.
为或,& 为和,~ 为非。 These must be grouped by using parentheses, since by default Python will evaluate an expression such as df.A > 2 & df.B < 3 as df.A > (2 & df.B) < 3, while the desired evaluation order is (df.A > 2) & (df.B < 3).
这些必须使用括号进行分组,因为默认情况下 Python 将评估表达式,例如 df.A > 2 & df.B < 3 as df.A > (2 & df.B) < 3,而所需的评估顺序是(df.A > 2) & (df.B < 3)。
Thus, adding the brackets to your last line should work:因此,将括号添加到最后一行应该可以:
df_t = df[(df['datetime']>=t) & (df['datetime']<t_end)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.