第十四章 数据分析示例
接下来本章为大家讲解一些数据分析示例
注:本章示例数据集可在附带的GitHub仓库(http://github.com/wesm/pydata-book)中找到
14.1 从Bitly获取1.USA.gov数据
2011年,短网址服务商Bitly(https://bitly.com/)与美国政府网站USA.gov(https://www. usa.gov/)合作,提供从以.gov或.mil结尾的短网址的用户收集的匿名数据。2011年,可以下载的文本文件提供实时供稿和小时快照。在撰写本书时(2017年)此服务已关闭,但我们保留了一个数据文件作为本书的示例。
在每小时快照的情况下,每个文件中的每一行都包含一种通用形式的web数据,称为JSON,它是JavaScript Object Notation的简写。
Python拥有用于将JSON字符串转换为Python字典对象的内置和第三方库。
示例:只读取文件的第一行,然后在我们下载的示例文件的每一行中使用json模块及其loads函数(见图14-1)

注:对象records现在是一个Python字典的列表。
14.1.1 纯Python时区计数
假设我们想要找到数据集中最常出现的时区(tz字段)。有很多方法可以实现这一点。
1.首先,我们使用列表再次提取时区列表(见图14-2)

2.按时区生成计数(仅使用Python标准库)
计数方法之一:在遍历时区时使用字典来存储计数(见图14-3)

3.做一些字典技巧以获取前十的时区和它们的计数(见图14-4、14-5)


14.1.2 使用pandas进行时区计数
1.根据原始的记录集合生成DataFrame非常简单,只需要把记录的列表传递给pandas. DataFrame(见图14-6)

2.frame的输出显示的是概要视图,用于展示大型DataFrame对象。对于Series,我们可以使用value_counts方法。(见图14-7)

3.清理数据
使用matplotlib对这些数据可视化时,可以进行一些清理工作,以便为记录中的未知和缺失的时区数据填入替代值。我们用fillna方法替换缺失值,并为空字符串使用布尔数组索引。(见图14-8)

4.可视化
使用seaborn包(http://seaborn.pydata.org/)来绘制一个水平柱状图(见图14-9)

5.a列包含了执行网址缩短的浏览器、设备或应用的信息(见图14-10)

6.分离字符串中的第一个标记(粗略地对应于浏览器功能),并对用户行为进行另一个概括,解析这些“代理”字符串中的所有感兴趣的信息(见图14-11)

注:(1)Series.str.split(pat=None,n=-1,expand=False)
Split strings around given separator/delimiter.
(2)DataFrame.dropna(axis=0,how='any',thresh=None,subset=None,inplace=False)
Remove missing values.
7.将时区计数多的时区记录分解为Windows和非Windows用户。
作为简化,如果字符串’Windows’在代理字符串中,我们就认为用户在Windows上。(见图14-12)

8.使用size分组计数
与value_counts函数类似,分组计数可以使用size计算。然后可以使用unstack对计算结果进行重塑 (见图14-13)

9.选出总体计数最高的时区
要实现这个功能,首先在agg_counts中根据行的计数构造了一个间接索引数组;
然后使用take方法按顺序选出行,之后再对最后10行进行切片(最大的10个值)。(见图14-14)

补充: pandas有一个便捷的方法叫作nlargest,可以做同样的事情(见图14-15)

绘制条形图(可视化)绘制一个堆积条形图(见图14-16)

该图不容易看到较小组中的Windows用户的相对百分比,因此让我们将组百分比归一化为1,然后重新绘图(见图14-17)

附:更有效的归一化算法(见图14-18)

注:(1)numpy.argsort(a,axis=-1,kind='quicksort',order=None)
Returns the indices that would sort an array.
(2)Series.argsort(axis=0,kind='quicksort',order=None)
Overrides ndarray.argsort. Argsorts the value, omitting NA/null values, and places the result in the same locations as the non-NA values
(3)DataFrame.reset_index(level=None,drop=False,inplace=False,col_level=0,col_fill='')
For DataFrame with multi-level index, return new DataFrame with labeling information in the columns under the index names, defaulting to ‘level_0’, ‘level_1’, etc. if any are None. For a standard index, the index name will be used (if set), otherwise a default ‘index’ or ‘level_0’ (if ‘index’ is already taken) will be used.
网友评论