Python數(shù)據(jù)分析之真實(shí)IP請(qǐng)求Pandas詳解
前言
pandas 是基于 Numpy 構(gòu)建的含有更高級(jí)數(shù)據(jù)結(jié)構(gòu)和工具的數(shù)據(jù)分析包類似于 Numpy 的核心是 ndarray,pandas 也是圍繞著 Series 和 DataFrame 兩個(gè)核心數(shù)據(jù)結(jié)構(gòu)展開的 。Series 和 DataFrame 分別對(duì)應(yīng)于一維的序列和二維的表結(jié)構(gòu)。pandas 約定俗成的導(dǎo)入方法如下:
from pandas import Series,DataFrame import pandas as pd
1.1. Pandas分析步驟
1、載入日志數(shù)據(jù)
2、載入area_ip數(shù)據(jù)
3、將 real_ip 請(qǐng)求數(shù) 進(jìn)行 COUNT。類似如下SQL:
SELECT inet_aton(l.real_ip), count(*), a.addr FROM log AS l INNER JOIN area_ip AS a ON a.start_ip_num <= inet_aton(l.real_ip) AND a.end_ip_num >= inet_aton(l.real_ip) GROUP BY real_ip ORDER BY count(*) LIMIT 0, 100;
1.2. 代碼
cat pd_ng_log_stat.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from ng_line_parser import NgLineParser
import pandas as pd
import socket
import struct
class PDNgLogStat(object):
def __init__(self):
self.ng_line_parser = NgLineParser()
def _log_line_iter(self, pathes):
"""解析文件中的每一行并生成一個(gè)迭代器"""
for path in pathes:
with open(path, 'r') as f:
for index, line in enumerate(f):
self.ng_line_parser.parse(line)
yield self.ng_line_parser.to_dict()
def _ip2num(self, ip):
"""用于IP轉(zhuǎn)化為數(shù)字"""
ip_num = -1
try:
# 將IP轉(zhuǎn)化成INT/LONG 數(shù)字
ip_num = socket.ntohl(struct.unpack("I",socket.inet_aton(str(ip)))[0])
except:
pass
finally:
return ip_num
def _get_addr_by_ip(self, ip):
"""通過(guò)給的IP獲得地址"""
ip_num = self._ip2num(ip)
try:
addr_df = self.ip_addr_df[(self.ip_addr_df.ip_start_num <= ip_num) &
(ip_num <= self.ip_addr_df.ip_end_num)]
addr = addr_df.at[addr_df.index.tolist()[0], 'addr']
return addr
except:
return None
def load_data(self, path):
"""通過(guò)給的文件路徑加載數(shù)據(jù)生成 DataFrame"""
self.df = pd.DataFrame(self._log_line_iter(path))
def uv_real_ip(self, top = 100):
"""統(tǒng)計(jì)cdn ip量"""
group_by_cols = ['real_ip'] # 需要分組的列,只計(jì)算和顯示該列
# 直接統(tǒng)計(jì)次數(shù)
url_req_grp = self.df[group_by_cols].groupby(
self.df['real_ip'])
return url_req_grp.agg(['count'])['real_ip'].nlargest(top, 'count')
def uv_real_ip_addr(self, top = 100):
"""統(tǒng)計(jì)real ip 地址量"""
cnt_df = self.uv_real_ip(top)
# 添加 ip 地址 列
cnt_df.insert(len(cnt_df.columns),
'addr',
cnt_df.index.map(self._get_addr_by_ip))
return cnt_df
def load_ip_addr(self, path):
"""加載IP"""
cols = ['id', 'ip_start_num', 'ip_end_num',
'ip_start', 'ip_end', 'addr', 'operator']
self.ip_addr_df = pd.read_csv(path, sep='\t', names=cols, index_col='id')
return self.ip_addr_df
def main():
file_pathes = ['www.ttmark.com.access.log']
pd_ng_log_stat = PDNgLogStat()
pd_ng_log_stat.load_data(file_pathes)
# 加載 ip 地址
area_ip_path = 'area_ip.csv'
pd_ng_log_stat.load_ip_addr(area_ip_path)
# 統(tǒng)計(jì) 用戶真實(shí) IP 訪問(wèn)量 和 地址
print pd_ng_log_stat.uv_real_ip_addr()
if __name__ == '__main__':
main()
運(yùn)行統(tǒng)計(jì)和輸出結(jié)果
python pd_ng_log_stat.py
count addr
real_ip
60.191.123.80 101013 浙江省杭州市
- 32691 None
218.30.118.79 22523 北京市
......
136.243.152.18 889 德國(guó)
157.55.39.219 889 美國(guó)
66.249.65.170 888 美國(guó)
[100 rows x 2 columns]
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。
- Python數(shù)據(jù)分析模塊pandas用法詳解
- Python數(shù)據(jù)分析庫(kù)pandas基本操作方法
- Python數(shù)據(jù)分析之如何利用pandas查詢數(shù)據(jù)示例代碼
- 基于Python數(shù)據(jù)分析之pandas統(tǒng)計(jì)分析
- Python數(shù)據(jù)分析pandas模塊用法實(shí)例詳解
- Python數(shù)據(jù)分析庫(kù)pandas高級(jí)接口dt的使用詳解
- 詳解Python數(shù)據(jù)分析--Pandas知識(shí)點(diǎn)
- Python Pandas數(shù)據(jù)分析工具用法實(shí)例
- Python入門之使用pandas分析excel數(shù)據(jù)
- python利用pandas分析學(xué)生期末成績(jī)實(shí)例代碼
相關(guān)文章
python數(shù)字圖像處理實(shí)現(xiàn)直方圖與均衡化
在圖像處理中,直方圖是非常重要,也是非常有用的一個(gè)處理要素。這篇文章主要介紹了python數(shù)字圖像處理實(shí)現(xiàn)直方圖與均衡化,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
對(duì)pandas進(jìn)行數(shù)據(jù)預(yù)處理的實(shí)例講解
下面小編就為大家分享一篇對(duì)pandas進(jìn)行數(shù)據(jù)預(yù)處理的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
淺談Python使用pickle模塊序列化數(shù)據(jù)優(yōu)化代碼的方法
這篇文章主要介紹了淺談Python使用pickle模塊序列化數(shù)據(jù)優(yōu)化代碼的方法,pickle模塊可以對(duì)多種Python對(duì)象進(jìn)行序列化和反序列化,序列化稱為pickling,反序列化稱為unpickling,需要的朋友可以參考下2023-07-07
python GUI庫(kù)圖形界面開發(fā)之PyQt5 Qt Designer工具(Qt設(shè)計(jì)師)詳細(xì)使用方法及Designer
這篇文章主要介紹了python GUI庫(kù)圖形界面開發(fā)之PyQt5 Qt Designer工具(Qt設(shè)計(jì)師)詳細(xì)使用方法及Designer ui文件轉(zhuǎn)py文件方法,需要的朋友可以參考下2020-02-02
使用Python連接MySQL數(shù)據(jù)庫(kù)進(jìn)行編程的步驟詳解
Python數(shù)據(jù)庫(kù)編程可以使用多種模塊與API,例如SQLite、MySQL、PostgreSQL等,本教程將重點(diǎn)介紹使用Python連接MySQL數(shù)據(jù)庫(kù)進(jìn)行編程,需要的朋友可以參考下2023-06-06
Python Numpy實(shí)現(xiàn)修改數(shù)組形狀
NumPy(Numerical Python)是Python中用于處理數(shù)組和矩陣的重要庫(kù),它提供了豐富的功能,用于科學(xué)計(jì)算,本文主要介紹了如何使用NumPy提供的方法來(lái)改變數(shù)組的形狀,感興趣的可以了解下2023-11-11
從零學(xué)python系列之淺談pickle模塊封裝和拆封數(shù)據(jù)對(duì)象的方法
這個(gè)系列也發(fā)了幾篇文章了,都是個(gè)人的一些學(xué)習(xí)心得的記錄,今天在學(xué)習(xí)文件數(shù)據(jù)處理的時(shí)候了解到有pickle模塊,查找官方文檔學(xué)習(xí)了一些需要用到的pickle內(nèi)容。2014-05-05

