使用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']] 使 ...
随机推荐
- oracle中schema指的是什么?
看来有的人还是对schema的真正含义不太理解,现在我再次整理了一下,希望对大家有所帮助. 我们先来看一下他们的定义:A schema is a collection of database obje ...
- $.post 请求一直转圈圈,谷歌浏览器状态一直为canceled
最开始写的是 $.post("url",{},function(){},"json") 用火狐浏览器 测试发现请求一直在转圈圈 ,就在action输出 发现也进 ...
- [原]Wpf应用Path路径绘制圆弧
1. 移动指令:Move Command(M):M 起始点 或者:m 起始点比如:M 100,240或m 100,240使用大写M时,表示绝对值; 使用小写m时; 表示相对于前一点的值,如果前一点没 ...
- iOS开发UI篇—推荐两个好用的Xcode插件(提供下载链接)
iOS开发UI篇—推荐两个好用的Xcode插件(提供下载链接) 这里推荐两款好用的Xcode插件,并提供下载链接. 一.插件和使用如下: 1.两款插件 对项目中图片提供自动提示功能的插件:KSImag ...
- PHP的GD 支持和加载MySQL功能
本机安装dedecms时发现, GD 支持 On [×]Off (不支持将导致与图片相关的大多数功能无法使用或引发警告) MySQL 支持 On [×]Off (不支持无法使用本系统) 错误,原来是环 ...
- iOS开发中可能有用的那些分类们Categories
Categories是给你得不到源码的classes增加功能的一种方法. UIImageView+FaceAwareFill 这个类别使用了Aspect Fill内容模式,可以自动根据图像内容进行调整 ...
- PureLayout和Masonry比较
一年前那时我做iOS开发,为了自动布局适配多种屏幕,我一般使用Masonry,后来偶然地在一个视频教程中发现老师使用了UIView+Autolayout(现在作者改名为PureLayout)自动布局, ...
- android_permission权限大全
访问登记属性 android.permission.ACCESS_CHECKIN_PROPERTIES ,读取或写入登记check-in数据库属性表的权限 获取错略位置 android.permiss ...
- QUICK START GUIDE
QUICK START GUIDE This page is a guide aimed at helping anyone set up a cheap radio scanner based on ...
- Win10/UWP新特性系列—Launcher实现应用间的通信
UWP中,微软为Windows.System.Launcher启动器新增了很多的功能,以前只能启动App,打开指定扩展名文件,对uri协议的解析,以及当启动的应用没有安装时则会提示前往商店下载等. 如 ...