使用pandas处理数据并绘图的例子
import sys
import os
import re
import datetime
import csv def get_datetime(record):
request_time = ""
p = re.compile(r"(?P<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d+)")
# p = re.compile(r"(?P<time>[\d.]+)ms")
m = p.search(record)
if m:
request_time = m.group("time")
dt = datetime.datetime.strptime(request_time, '%Y-%m-%d %H:%M:%S,%f')
return dt def parse(log_file_name, result_csv_name):
start = 0
end = 0
start_time = ''
end_time = ''
md5crc32 = ''
csv_writer = csv.writer(open(result_csv_name, 'wb'),
delimiter = ',')
with open(log_file_name, 'rb') as log_file:
for i, line in enumerate(log_file):
line = line.strip()
if 'folderProcessing() INFO download from' in line:
start = i
start_time = get_datetime(line)
elif 'DownLoadFile() INFO download to' in line:
end = i
end_time = get_datetime(line)
# got one download action
if end - start == 1:
# parse hash
md5crc32 = line.rsplit('/', 1)[1]
print md5crc32, (end_time - start_time).total_seconds()
csv_writer.writerow((md5crc32, (end_time - start_time).total_seconds()))
# assert False def do_statistics(file_name):
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv(file_name, header = None, names= ['hash', 'time'], dtype = {'time': np.float64},
# nrows = 10000
)
time_series = df.time
print time_series.describe()
plt.figure()
# fig = time_series.hist().get_figure()
# define range
ranges = (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 2.0, 3.0, 4.0, 10.0, 10000)
bins = zip(ranges[:-1], ranges[1:])
labels = ['%s-%s'%(begin, end) for i ,(begin, end) in enumerate(bins) ]
print labels
#print bins
#fig = time_series.plot(kind='bar', xticks = ranges)
results = [0] * len(bins)
for i in time_series:
for j , (begin, end) in enumerate(bins):
if i > begin and i <= end:
results[j] += 1
print results mu = time_series.mean()
median = np.median(time_series)
sigma = time_series.std() ax = pd.Series(results).plot(kind='bar', logy = True, figsize=(25, 13.5))
# dpi = ax.figure.get_dpi()
# print 'dpi = ', dpi
# plt.gcf().set_size_inches(25, 13.5) ax.set_ylabel('Count')
ax.set_xlabel('Time in seconds')
# print dir(fig)
ax.set_xticklabels(labels, rotation = 45)
ax.set_title('MDSS download statistics') textstr = 'count=%s\nmin=%.2f\nmax=%.2f\n$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(time_series.count(),time_series.min(), time_series.max(),mu, median, sigma) # these are matplotlib.patch.Patch properties
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) # place a text box in upper right in axes coords
ax.text(0.90, 0.95, textstr, transform=ax.transAxes, fontsize=14,
verticalalignment='top', bbox=props) ax.figure.show()
#
ax.figure.set_size_inches(25, 13.5, forward = True)
print ax.figure.get_size_inches()
ax.figure.savefig('result.png', format='png',)
input('asdfasd') if __name__ == "__main__":
# print get_datetime("2014-10-23 09:19:34,251 pid=27850")
# parse('inpri_p_antiy.log', 'result.csv')
do_statistics('result.csv')
生成图像如下:

使用pandas处理数据并绘图的例子的更多相关文章
- 利用Python进行数据分析(12) pandas基础: 数据合并
pandas 提供了三种主要方法可以对数据进行合并: pandas.merge()方法:数据库风格的合并: pandas.concat()方法:轴向连接,即沿着一条轴将多个对象堆叠到一起: 实例方法c ...
- 【转载】使用Pandas对数据进行筛选和排序
使用Pandas对数据进行筛选和排序 本文转载自:蓝鲸的网站分析笔记 原文链接:使用Pandas对数据进行筛选和排序 目录: sort() 对单列数据进行排序 对多列数据进行排序 获取金额最小前10项 ...
- 【转载】使用Pandas进行数据提取
使用Pandas进行数据提取 本文转载自:蓝鲸的网站分析笔记 原文链接:使用python进行数据提取 目录 set_index() ix 按行提取信息 按列提取信息 按行与列提取信息 提取特定日期的信 ...
- 【转载】使用Pandas进行数据匹配
使用Pandas进行数据匹配 本文转载自:蓝鲸的网站分析笔记 原文链接:使用Pandas进行数据匹配 目录 merge()介绍 inner模式匹配 lefg模式匹配 right模式匹配 outer模式 ...
- 【转载】使用Pandas创建数据透视表
使用Pandas创建数据透视表 本文转载自:蓝鲸的网站分析笔记 原文链接:使用Pandas创建数据透视表 目录 pandas.pivot_table() 创建简单的数据透视表 增加一个行维度(inde ...
- Pandas 把数据写入csv
Pandas 把数据写入csv from sklearn import datasets import pandas as pd iris = datasets.load_iris() iris_X ...
- pandas学习(数据分组与分组运算、离散化处理、数据合并)
pandas学习(数据分组与分组运算.离散化处理.数据合并) 目录 数据分组与分组运算 离散化处理 数据合并 数据分组与分组运算 GroupBy技术:实现数据的分组,和分组运算,作用类似于数据透视表 ...
- Pandas DataFrame数据的增、删、改、查
Pandas DataFrame数据的增.删.改.查 https://blog.csdn.net/zhangchuang601/article/details/79583551 #删除列 df_2 = ...
- pandas 选取数据 修改数据 loc iloc []
pandas选取数据可以通过 loc iloc [] 来选取 使用loc选取某几列: user_fans_df = sample_data.loc[:,['uid','fans_count']] 使 ...
随机推荐
- 张艾迪(创始人):创始人故事无限N个
世界第一女孩+世界第一互联网女孩 创始人故事无限N个 全球第一互联网女孩EidyZhang艾迪.张 The World No.1 Girl :Eidyzhang The World No.1 Inte ...
- ListView.DragEnter触发不了
经过千百度的搜索之后,终于找到了一点线索,原文是:https://msdn.microsoft.com/en-us/magazine/mt185571.aspx 有能力的可以参阅原文,想省事的可以等待 ...
- 常见JAVA框架
Spring Framework [Java开源JEE框架] Spring是一个解决了许多在J2EE开发中常见的问题的强大框架. Spring提供了管理业务对象的一致方法并且鼓励了注入对接口编程而不 ...
- HighCharts绘制图表
<div id="TradeMoney"></div> <script> $(function () { initData(); }); fun ...
- 项目中使用oracle序列
在数据库设计的时候我们可以将表的ID定义为String 然后我们可以使用序列来得到唯一的ID 手写一个mapper: <?xml version="1.0" encoding ...
- 58.com qiyi
using AnfleCrawler.Common; using System; using System.Collections.Generic; using System.Linq; using ...
- php 判断复选框checkbox是否被选中
php 判断复选框checkbox是否被选中 复选框checkbox在php表单提交中经常被使用到,本文章通过实例向大家介绍php如何判断复选框checkbox中的值是否被选中,需要的朋友可以参考 ...
- POJ 1236 SCC+缩点
题意:一张有向图,一问至少给几个点发送软件,才能让所有点都能收到软件:二问是至少添加几条边才能让整个图是一个连通分量: 分析:一般求连通分量都会求缩点,在这里缩点之后,生成一张新的图,在新的图中求每一 ...
- 【LeetCode OJ】Balanced Binary Tree
Problem Link: http://oj.leetcode.com/problems/balanced-binary-tree/ We use a recursive auxilar funct ...
- activity 和 生命周期: 消息通信
实际上关于activity大概流程已经了解了,在深入的话方向应该是ams的处理操作和界面创建和view绘制.这些话题之后再谈,activity是一个gui程序,其中离不开的就是消息通讯,也就是在消息循 ...