簡體   English   中英

對於 pandas dataframe 中的每一行,檢查列是否包含最后 5 行中的字符串

[英]For every row in a pandas dataframe, check if a column contains a string in in the last 5 rows

[Date]                  [Etype]        [IP]           [Device]   [Event]                  
1 2020-08-19 23:02:29    Daemon.Emerg  xx.xxx.xx.xx    True   CHASSIS-POWER_STATUS_FAILURE      
2 2020-08-19 23:03:57  Daemon.Warning  xx.xxx.xx.xx    True   CHASSIS-TIME_CHANGED_FORWARD     
3 2020-08-19 23:03:57    Daemon.Emerg  xx.xxx.xx.xx    True  NTPC-NTP_FIRST_SYNCH_ACHIEVED     
4 2020-08-19 23:04:13    Daemon.Alert  xx.xxx.xx.xx    True    CFM-CFM_SERVICE_FAULT_CLEAR      
5 2020-08-19 23:06:27  Daemon.Warning  xx.xxx.xx.xx    True         PORT-STATE_CHANGE__R_T      

以上是我正在使用的 dataframe 的片段。 我想要做的是對於每一行,檢查第二列的前 5 個系列元素是否包含一個字符串,有點像向下移動該列的 FIFO 列表。

如果我能得到一個在日期時間之間進行檢查但間隔不統一的 5 行長的列表,我會很高興

df['Flag'] = df['Etype'].str.contains("Daemon.Emerg").between(current index datetime: 5 rows previous datetime)

我不確定如何使用索引執行此操作

基本思想是使用shift獲取前 n 行的 etype。 我們必須多次執行此操作才能獲得前五行。 然后我們將這些結果合並為一列。 解析起來有點困難,但我們可以通過列表理解來做到這一點:

# shift then filter out any nan's that occur when prior row is unavailable,
# then use ', '.join() to combine results. 
# Use list comprehension to do this for each row and for each shift.

df['prev'] = [', '.join([str(df['[Etype]'].shift(i).values[j]) 
                         for i in range(1, 6) 
                         if str(df['[Date]'].shift(i).values[j]) != 'nan']) 
              for j in range(5)]

然后您可以使用df.prev.str.contains檢查您想要的內容

查看 pd.rolling,它似乎符合我的描述。 以下對我有用:

    df['Prev'] = [x.values.tolist()[:-1] for x in df['Etype'].rolling(N)]
    df['Prev5_flag'] = ciena_df['Prev'].str.contains("Daemon.Emerg", regex=False)

暫無
暫無

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

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