簡體   English   中英

循環通過指定范圍內的 python 日期時間 TypeError

[英]loop through python datetimes in specified range TypeError

我想在 t_list 指定的時間段內每 10 分鍾創建一個散點圖t_list 我收到錯誤TypeError: cannot compare a dtyped [datetime64[ns]] array with a scalar of type [bool] df_t = df[(df['datetime']>=t & df['datetime']<t_end)]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

當 boolean 索引具有多個條件時,您應該將每個單個條件括在括號中。

從文檔:

另一種常見的操作是使用 boolean 向量來過濾數據。 運算符是: | 為或,& 為和,~ 為非。 這些必須使用括號進行分組,因為默認情況下 Python 將評估表達式,例如 df.A > 2 & df.B < 3 as df.A > (2 & df.B) < 3,而所需的評估順序是(df.A > 2) & (df.B < 3)。

因此,將括號添加到最后一行應該可以:

df_t = df[(df['datetime']>=t) & (df['datetime']<t_end)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM