Python數(shù)據(jù)分析之真實IP請求Pandas詳解
前言
pandas 是基于 Numpy 構建的含有更高級數(shù)據(jù)結構和工具的數(shù)據(jù)分析包類似于 Numpy 的核心是 ndarray,pandas 也是圍繞著 Series 和 DataFrame 兩個核心數(shù)據(jù)結構展開的 。Series 和 DataFrame 分別對應于一維的序列和二維的表結構。pandas 約定俗成的導入方法如下:
from pandas import Series,DataFrame import pandas as pd
1.1. Pandas分析步驟
1、載入日志數(shù)據(jù)
2、載入area_ip數(shù)據(jù)
3、將 real_ip 請求數(shù) 進行 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): """解析文件中的每一行并生成一個迭代器""" 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轉化為數(shù)字""" ip_num = -1 try: # 將IP轉化成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): """通過給的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): """通過給的文件路徑加載數(shù)據(jù)生成 DataFrame""" self.df = pd.DataFrame(self._log_line_iter(path)) def uv_real_ip(self, top = 100): """統(tǒng)計cdn ip量""" group_by_cols = ['real_ip'] # 需要分組的列,只計算和顯示該列 # 直接統(tǒng)計次數(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)計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)計 用戶真實 IP 訪問量 和 地址 print pd_ng_log_stat.uv_real_ip_addr() if __name__ == '__main__': main()
運行統(tǒng)計和輸出結果
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 德國 157.55.39.219 889 美國 66.249.65.170 888 美國 [100 rows x 2 columns]
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作帶來一定的幫助,如果有疑問大家可以留言交流。
- Python數(shù)據(jù)分析模塊pandas用法詳解
- Python數(shù)據(jù)分析庫pandas基本操作方法
- Python數(shù)據(jù)分析之如何利用pandas查詢數(shù)據(jù)示例代碼
- 基于Python數(shù)據(jù)分析之pandas統(tǒng)計分析
- Python數(shù)據(jù)分析pandas模塊用法實例詳解
- Python數(shù)據(jù)分析庫pandas高級接口dt的使用詳解
- 詳解Python數(shù)據(jù)分析--Pandas知識點
- Python Pandas數(shù)據(jù)分析工具用法實例
- Python入門之使用pandas分析excel數(shù)據(jù)
- python利用pandas分析學生期末成績實例代碼
相關文章
python數(shù)字圖像處理實現(xiàn)直方圖與均衡化
在圖像處理中,直方圖是非常重要,也是非常有用的一個處理要素。這篇文章主要介紹了python數(shù)字圖像處理實現(xiàn)直方圖與均衡化,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05淺談Python使用pickle模塊序列化數(shù)據(jù)優(yōu)化代碼的方法
這篇文章主要介紹了淺談Python使用pickle模塊序列化數(shù)據(jù)優(yōu)化代碼的方法,pickle模塊可以對多種Python對象進行序列化和反序列化,序列化稱為pickling,反序列化稱為unpickling,需要的朋友可以參考下2023-07-07python GUI庫圖形界面開發(fā)之PyQt5 Qt Designer工具(Qt設計師)詳細使用方法及Designer
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5 Qt Designer工具(Qt設計師)詳細使用方法及Designer ui文件轉py文件方法,需要的朋友可以參考下2020-02-02使用Python連接MySQL數(shù)據(jù)庫進行編程的步驟詳解
Python數(shù)據(jù)庫編程可以使用多種模塊與API,例如SQLite、MySQL、PostgreSQL等,本教程將重點介紹使用Python連接MySQL數(shù)據(jù)庫進行編程,需要的朋友可以參考下2023-06-06Python Numpy實現(xiàn)修改數(shù)組形狀
NumPy(Numerical Python)是Python中用于處理數(shù)組和矩陣的重要庫,它提供了豐富的功能,用于科學計算,本文主要介紹了如何使用NumPy提供的方法來改變數(shù)組的形狀,感興趣的可以了解下2023-11-11從零學python系列之淺談pickle模塊封裝和拆封數(shù)據(jù)對象的方法
這個系列也發(fā)了幾篇文章了,都是個人的一些學習心得的記錄,今天在學習文件數(shù)據(jù)處理的時候了解到有pickle模塊,查找官方文檔學習了一些需要用到的pickle內容。2014-05-05