这边我们使用内存分析框架Pandas来分析每日PV。
其实个人对Pandas这个模块是颇有好感。本人用Pandas完成可许多的日常实用的小工具,如生产excel报表,简单数据迁移等等。
对我来说Pandas就是一个内存的MySQL,我通常叫他为 程序式SQL。
1 | SELECT DATE_FORMAT ( access_time , ‘%Y-%m-%d’ ) , count ( * ) FROM log GROUP BY DATE_FORMAT ( access_time , ‘%Y-%m-%d’ ) ; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 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 load_data ( self , path ) : “” “通过给的文件路径加载数据生成 DataFrame” “” self . df = pd . DataFrame ( self . _log_line_iter ( path ) ) def pv_day ( self ) : “” “计算每一天的 PV” “” group_by_cols = [ ‘access_time’ ] # 需要分组的列,只计算和显示该列 # 下面我们是按 yyyy-mm-dd 形式来分组的, 所以需要定义分组策略: # 分组策略为: self.df[‘access_time’].map(lambda x: x.split()[0]) pv_day_grp = self . df [ group_by_cols ] . groupby ( self . df [ ‘access_time’ ] . map ( lambda x : x . split ( ) [ 0 ] ) ) return pv_day_grp . agg ( [ ‘count’ ] ) def main ( ) : file_pathes = [ ‘www.trustauth.cn.access.log’ ] pd_ng_log_stat = PDNgLogStat ( ) pd_ng_log_stat . load_data ( file_pathes ) # 统计每日 pv print pd_ng_log_stat . pv_day ( ) if __name__ == ‘__main__’ : main ( ) |
运行统计和输出结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | python pd_ng_log_stat . py access_time count access _time 2016 – 06 – 13 4149 2016 – 06 – 14 10234 2016 – 06 – 15 9825 . . . . . . 2016 – 09 – 16 11076 2016 – 09 – 17 10231 2016 – 09 – 18 6739 [ 98 rows x 1 columns ] |
文章转载来自:trustauth.cn