首页 > 解决方案 > Pandas - 检查数据框中的重复模式

问题描述

我目前正在尝试用熊猫分析网络数据。我一直在阅读其他帖子,最接近我的问题的是Pandas - Find and index rows that match row sequence pattern

我的数据框如下所示: 数据框

我正在尝试检查某些包裹是否丢失并计算丢失包裹的数量。因此,我想定义一个窗口或矩阵,这里是 2x2。然后定义一个模式,在这种情况下它将是.

现在我想检查窗口是否完全是一个循环窗口。如果可能的话,这应该在一个额外的列中完成,给我 false 或 true(或 nan)。我已经在我的代码的以下示例中尝试了这一点。

在第一个示例中,我尝试通过迭代行来检查它。我的第三个示例更符合我的要求:使用滚动命令,我定义了一个窗口和一个模式,代码应该检查行,但我得到一个错误,因为模式是一个字符串。这就是我希望它看起来的样子。

import pandas as pd

df = pd.read_csv('你好')

在这里我过滤掉干扰

   Protocol_filtered = df[df['Protocol']== 'ICMP']
   Protocol_filtered1 = Protocol_filtered[['Time','Source','Destination','Info']] 
   Protocol_filtered1 = Protocol_filtered1.reset_index(drop=True)

我开始检查丢失的包裹

    s0 = 0
    s1 = 1

   for row in Protocol_filtered1.iterrows():
  while s1 <= len (Protocol_filtered1):
    source = Protocol_filtered1.loc[s0,'Source']
    dest = Protocol_filtered1.loc[s1,'Destination']

    if source == dest:
        Protocol_filtered1['Check']= True
    else:
        Protocol_filtered1['Check']= False
    
    source1 = Protocol_filtered1.loc[s1,'Source']
    dest1 = Protocol_filtered1.loc[s0,'Destination']
    


    if source1 == dest1:
        Protocol_filtered1['Check1']= True
    else:
        Protocol_filtered1['Check1']= False

    s0 = s0 + 2
    s1 = s1 + 2  

这段代码的结果不是我想要的结果,因为它在第 2 行给了我一个真值,它应该是假的。

Protocol_filtered1.head()

以下代码的逻辑是正确的,但它会检查每一行的 i,而它应该始终同时检查两个连续的行 (0 & 1, 2&3 ,4&5 ...):

pattern = ['192.168.20.35', '192.168.20.31']
i = (Protocol_filtered1['Source'] == '192.168.20.35') &         (Protocol_filtered1['Source'].shift(-1) == '192.168.20.31')
i &= (Protocol_filtered1['Destination'] == '192.168.20.31') & (Protocol_filtered1['Destination'].shift(-1)== '192.168.20.35')

Protocol_filtered1.index[i]

Protocol_filtered1 ['Check1'] = i

这里的结果是(应该是:检查:真、真、假、假、真、真):

在此处输入图像描述

我在论坛中找到并尝试应用的一个非常优雅的解决方案是:

pattern = ['192.168.20.35', '192.168.20.31']
obs = len(pattern)
Protocol_filtered1['S1'] = (Protocol_filtered1['Source']
                        .rolling(window = obs, min_periods = )
                        .apply(lambda x: (x==pattern).all())
                        .astype(bool)
                        .shift(-1*(obs-1)))

但是我的代码似乎也存在问题。我更喜欢最后一个解决方案,我可以定义特定的模式和窗口的大小,然后让 pandas 遍历所有数据框,然后我可以使用 isnull() 计算丢失的包裹数量。

我真的很感激一些帮助!非常感谢!

标签: pythonpandasdataframepattern-matching

解决方案


推荐阅读