Python資料分析之真實IP請求Pandas詳解,pythonpandas

來源:互聯網
上載者:User

Python資料分析之真實IP請求Pandas詳解,pythonpandas

前言

pandas 是基於 Numpy 構建的含有更進階資料結構和工具的資料分析包類似於 Numpy 的核心是 ndarray,pandas 也是圍繞著 Series 和 DataFrame 兩個核心資料結構展開的 。Series 和 DataFrame 分別對應於一維的序列和二維的表結構。pandas 約定俗成的匯入方法如下:

from pandas import Series,DataFrameimport pandas as pd

1.1. Pandas分析步驟

    1、載入日誌資料

    2、載入area_ip資料

    3、將 real_ip 請求數 進行 COUNT。類似如下SQL:

SELECT inet_aton(l.real_ip),  count(*),  a.addrFROM log AS lINNER 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_ipORDER 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 pdimport socketimport 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轉化為數字"""    ip_num = -1    try:      # 將IP轉化成INT/LONG 數字      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):    """通過給的檔案路徑載入資料產生 DataFrame"""    self.df = pd.DataFrame(self._log_line_iter(path))    def uv_real_ip(self, top = 100):    """統計cdn ip量"""    group_by_cols = ['real_ip'] # 需要分組的列,只計算和顯示該列         # 直接統計次數    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):    """統計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)   # 統計 使用者真實 IP 訪問量 和 地址  print pd_ng_log_stat.uv_real_ip_addr() if __name__ == '__main__':  main()

運行統計和輸出結果

python pd_ng_log_stat.py          count  addrreal_ip            60.191.123.80  101013 浙江省杭州市-        32691  None218.30.118.79  22523   北京市......136.243.152.18   889   德國157.55.39.219   889   美國66.249.65.170   888   美國 [100 rows x 2 columns]

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作帶來一定的協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.