【问题标题】:loop through python datetimes in specified range TypeError循环遍历指定范围 TypeError 中的 python 日期时间
【发布时间】:2020-02-14 16:00:35
【问题描述】:

我想在t_list 指定的时间段内每 10 分钟创建一个散点图。我在df_t = df[(df['datetime']>=t & df['datetime']<t_end)] 行中收到错误TypeError: cannot compare a dtyped [datetime64[ns]] array with a scalar of type [bool],但tt_end 的类型都是datetime。非变量类型为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

【问题讨论】:

  • 能否请您发布type(df['datetime'].iloc[0])type(t)type(t_end) 的输出?
  • pandas.tslib.Timestampdatetime.datetimedatetime.datetime 分别

标签: python python-2.7 datetime for-loop typeerror


【解决方案1】:

当布尔索引具有多个条件时,您应该将每个单个条件括在括号中。

来自文档:

另一个常见的操作是使用布尔向量来过滤 数据。运算符是: |为或,& 为和,~ 为非。 这些 必须使用括号进行分组,因为默认情况下 Python 会 评估表达式,例如 df.A > 2 & df.B (2 & df.B) 2) & (df.B

因此,将括号添加到最后一行应该可以:

df_t = df[(df['datetime']&gt;=t) &amp; (df['datetime']&lt;t_end)]

【讨论】:

  • 我总是错过一些简单的事情。谢谢你的信息
猜你喜欢
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 2020-03-06
  • 2023-02-17
  • 2011-05-19
  • 2011-02-19
  • 1970-01-01
  • 2012-02-21
相关资源
最近更新 更多