【问题标题】:Is there a quicker way of iterating through and removing specific rows in a Pandas dataframe?有没有更快的方法来遍历和删除 Pandas 数据框中的特定行?
【发布时间】:2018-06-13 05:33:06
【问题描述】:

我目前正在使用 Bat (https://github.com/Kitware/bat) 读取 Bro (https://www.bro.org/) 日志文件并将它们转换为 Pandas 数据帧。

我正在进行的工作之一是对 DNS 查找进行频率分析。此输出显示来自我的一个主机的价值一小时的 Bro dns 数据的大小,因此您可能会了解我正在处理的数据量。

bro_df.info()

<class 'bat.log_to_dataframe.LogToDataFrame'>
DatetimeIndex: 1013219 entries, 2018-01-03 08:59:53.250328 to 2018-01-03 09:59:51.672011
Data columns (total 23 columns):
AA             1013219 non-null bool
RA             1013219 non-null bool
RD             1013219 non-null bool
TC             1013219 non-null bool
TTLs           1013219 non-null object
Z              1013219 non-null int64
answers        1013219 non-null object
id.orig_h      1013219 non-null object
id.orig_p      1013219 non-null int64
id.resp_h      1013219 non-null object
id.resp_p      1013219 non-null int64
proto          1013219 non-null object
qclass         1013219 non-null int64
qclass_name    1013219 non-null object
qtype          1013219 non-null int64
qtype_name     1013219 non-null object
query          1013219 non-null object
rcode          1013219 non-null int64
rcode_name     1013219 non-null object
rejected       1013219 non-null bool
rtt            1013219 non-null timedelta64[ns]
trans_id       1013219 non-null int64
uid            1013219 non-null object
dtypes: bool(5), int64(7), object(10), timedelta64[ns](1)
memory usage: 151.7+ MB

我做了一些快速简单的事情,比如删除不必要的列等,但这仍然是一个相当大的数据框。

为了对查找进行适当的频率分析,我还尝试从数据框中删除“已知良好”或列入白名单的域,这就是事情变得真正缓慢的地方。由于我对 Pandas 还很陌生,所以我担心我可能会以一种不太理想的方式来做这件事,礼貌地说。

我删除白名单的方法如下 - 我删除了一些内部 DNS 信息以保护无辜者:

whitelist = ['-', '(empty)', 'in-addr.arpa', '.google.com', '.akamai.net', 
             '.akamaiedge.net', '.apple.com', '.contoso.msft']

for idx, row in bro_df.iterrows():
    for item in whitelist:
        if row['query'].endswith(item):
            bro_df.drop(idx, inplace=True)

即使在我将数据清理到比上面原始 bro_df.info() 输出显示的要少很多之后,这也需要很长时间才能完成。这个日志文件反映了一小时捕获的 DNS 查询,但删除白名单的内容需要超过一个小时,所以我在这里打一场失败的战斗。

任何帮助将不胜感激。

干杯,迈克

【问题讨论】:

    标签: python pandas loops dataframe jupyter-notebook


    【解决方案1】:

    我相信您需要str.contains,对于字符串的匹配结尾使用$ 并按boolean indexing 过滤:

    df = pd.DataFrame({'query':['-','dsds -','- sdsd']})
    print (df)
        query
    0       -
    1  dsds -
    2  - sdsd
    
    #() are escaped for remove warning 
    whitelist = ['-', '\(empty\)', 'in-addr.arpa', '.google.com', '.akamai.net', 
                 '.akamaiedge.net', '.apple.com', '.contoso.msft']
    
    
    pat = '|'.join([x + '$' for x in whitelist])
    
    df = df[~df['query'].str.contains(pat)]
    print (df)
        query
    2  - sdsd
    

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 2023-03-24
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2022-08-05
      • 2021-01-08
      • 2021-03-15
      • 2020-12-06
      相关资源
      最近更新 更多