如何在Pandas中获取host列所有高频值并转为列表?
问题
我有一批访问日志数据:
10.223.157.186 - - [15/Jul/2009:14:58:59 -0700] "GET / HTTP/1.1" 403 202 10.223.157.186 - - [15/Jul/2009:14:58:59 -0700] "GET /favicon.ico HTTP/1.1" 404 209 10.223.157.186 - - [15/Jul/2009:15:50:35 -0700] "GET / HTTP/1.1" 200 9157 10.211.47.159 - - [10/Aug/2009:20:52:19 -0700] "GET /assets/js/lowpro.js HTTP/1.1" 304 - 10.216.113.172 - - [12/Aug/2009:06:04:50 -0700] "GET /release-schedule/ HTTP/1.1" 200 9306 10.216.113.172 - - [12/Aug/2009:06:04:50 -0700] "GET /release-schedule/ HTTP/1.1" 200 9306 10.216.113.172 - - [12/Aug/2009:06:04:52 -0700] "GET /displaytitle.php?id=10 HTTP/1.1" 200 10234 10.216.113.172 - - [12/Aug/2009:06:04:52 -0700] "GET /displaytitle.php?id=10 HTTP/1.1" 200 10234
已经把日志里的host(比如10.223.157.186)存到了Pandas DataFrame的host列里。现在用这段代码找高频host:
result = Mainpanda['host'].mode() print("Mode:\n", result)
但只能拿到排名第一的高频值,我想获取排名1到N的所有高频host并转成列表,有没有办法实现?
解决方案
用value_counts()就能搞定,这个方法会直接按频次从高到低统计每个host的出现次数,比mode()灵活得多:
1. 统计并排序host频次
先执行统计:
host_counts = Mainpanda['host'].value_counts()
针对你的示例数据,这个结果是个Series,长这样:
10.216.113.172 4 10.223.157.186 3 10.211.47.159 1 Name: host, dtype: int64
2. 提取前N个高频host转列表
设置你需要的N值,然后用head(N)取前N个,再转成列表:
N = 2 # 替换成你要的数量 top_n_hosts = host_counts.head(N).index.tolist() print(top_n_hosts)
比如N=2时,输出就是:
['10.216.113.172', '10.223.157.186']
额外情况:处理并列高频的情况
如果有多个host频次相同(比如两个host都是最高频次),想把这些并列的都捞出来,可以这么写:
max_count = host_counts.iloc[0] top_hosts = host_counts[host_counts == max_count].index.tolist() print(top_hosts)
示例数据里最高频次是4,所以输出是:
['10.216.113.172']
内容的提问来源于stack exchange,提问作者user21131791
相关产品推荐
相关产品推荐

