gpt4 book ai didi

python - 有没有更快的方法来遍历和删除 Pandas 数据框中的特定行?

转载 作者:太空宇宙 更新时间:2023-11-04 04:51:52 26 4
gpt4 key购买 nike

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

我正在做的事情之一是对 DNS 查找进行一些频率分析。此输出显示来 self 的一台主机的一小时 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() 输出少很多之后,这也需要很长时间才能完成。这个日志文件反射(reflect)了一个小时捕获的 DNS 查询的值(value),但删除白名单的内容需要一个多小时的时间,所以我在这里打一场失败的战斗。

如有任何帮助,我们将不胜感激。

干杯,迈克

最佳答案

我相信你需要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

关于python - 有没有更快的方法来遍历和删除 Pandas 数据框中的特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48079133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com