来自bit.ly的1.usa.gov数据

2011年,URL缩短服务bit.ly跟美国政府网站usa.gov合作,提供了一份从生成.gov或.mil短链接的用户那里收集来的匿名数据译注1。直到编写本书时为止,除实时数据译注2之外,还可以下载文本文件形式的每小时快照注1

以每小时快照为例,文件中各行的格式为JSON(即JavaScript Object Notation,这是一种常用的Web数据格式)。例如,如果我们只读取某个文件中的第一行,那么你所看到的结果应该是下面这样:

  1. In [15]: path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
  2.  
  3. In [16]: open(path).readline()
  4. Out[16]: '{ "a": "Mozilla\\/5.0 (Windows NT 6.1; WOW64) AppleWebKit\\/535.11 (KHTML, like Gecko) Chrome\\/17.0.963.78 Safari\\/535.11", "c": "US", "nk": 1, "tz": "America\\/New_York", "gr": "MA", "g": "A6qOVH", "h": "wfLQtf", "l": "orofrog", "al": "en-US,en;q=0.8", "hh": "1.usa.gov", "r": "http:\\/\\/www.facebook.com\\/l\\/7AQEFzjSi\\/1.usa.gov\\/wfLQtf", "u": "http:\\/\\/www.ncbi.nlm.nih.gov\\/pubmed\\/22415991", "t": 1331923247, "hc":1331822918, "cy": "Danvers", "ll": [ 42.576698, -70.954903 ] }\n'

Python有许多内置或第三方模块可以将JSON字符串转换成Python字典对象。这里,我将使用json模块及其loads函数逐行加载已经下载好的数据文件:

  1. import json
  2. path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
  3. records = [json.loads(line) for line in open(path)]

你可能之前没用过Python,解释一下上面最后那行表达式,它叫做列表推导式(list comprehension),这是一种在一组字符串(或一组别的对象)上执行一条相同操作(如json.loads)的简洁方式。在一个打开的文件句柄上进行迭代即可获得一个由行组成的序列。现在,records对象就成为一组Python字典了:

  1. In [18]: records[0]
  2. Out[18]:
  3. {u'a': u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.78 Safari/535.11', u'al': u'en-US,en;q=0.8',
  4. u'c': u'US',
  5. u'cy': u'Danvers',
  6. u'g': u'A6qOVH',
  7. u'gr': u'MA',
  8. u'h': u'wfLQtf',
  9. u'hc': 1331822918,
  10. u'hh': u'1.usa.gov',
  11. u'l': u'orofrog',
  12. u'll': [42.576698, -70.954903],
  13. u'nk': 1,
  14. u'r': u'http://www.facebook.com/l/7AQEFzjSi/1.usa.gov/wfLQtf',
  15. u't': 1331923247,
  16. u'tz': u'America/New_York',
  17. u'u': u'http://www.ncbi.nlm.nih.gov/pubmed/22415991'}

注意,Python的索引是从0开始的,不像其他某些语言是从1开始的(如R)。现在,只要以字符串的形式给出想要访问的键就可以得到当前记录中相应的值了:

  1. In [19]: records[0]['tz']
  2. Out[19]: u'America/New_York'

单引号前面的u表示unicode(一种标准的字符串编码格式)。注意,IPython在这里给出的是时区的字符串对象形式,而不是其打印形式:

  1. In [20]: print records[0]['tz']
  2. America/New_York

用纯Python代码对时区进行计数

假设我们想要知道该数据集中最常出现的是哪个时区(即tz字段),得到答案的办法有很多。首先,我们用列表推导式取出一组时区:

  1. In [25]: time_zones = [rec['tz'] for rec in records]

KeyError Traceback (most recent call last) /home/wesm/book_scripts/whetting/<ipython> in <module>() ——> 1 time_zones = [rec['tz'] for rec in records]

KeyError: 'tz'

晕!原来并不是所有记录都有时区字段。这个好办,只需在列表推导式末尾加上一个if 'tz'in rec判断即可:

  1. In [26]: time_zones = [rec['tz'] for rec in records if 'tz' in rec]
  2.  
  3. In [27]: time_zones[:10]
  4. Out[27]:
  5. [u'America/New_York',
  6. u'America/Denver',
  7. u'America/New_York',
  8. u'America/Sao_Paulo',
  9. u'America/New_York',
  10. u'America/New_York',
  11. u'Europe/Warsaw',
  12. u'',
  13. u'',
  14. u'']

只看前10个时区,我们发现有些是未知的(即空的)。虽然可以将它们过滤掉,但现在暂时先留着。接下来,为了对时区进行计数,这里介绍两个办法:一个较难(只使用标准Python库),另一个较简单(使用pandas)。计数的办法之一是在遍历时区的过程中将计数值保存在字典中:

  1. def get_counts(sequence):
  2. counts = {}
  3. for x in sequence:
  4. if x in counts:
  5. counts[x] += 1
  6. else:
  7. counts[x] = 1
  8. return counts

如果非常了解Python标准库,那么你可能会将代码写得更简洁一些:

  1. from collections import defaultdict
  2.  
  3. def get_counts2(sequence):
  4. counts = defaultdict(int) # 所有的值均会被初始化为0
  5. for x in sequence:
  6. counts[x] += 1
  7. return counts

我将代码写到函数中是为了获得更高的可重用性。要用它对时区进行处理,只需将time_zones传入即可:

  1. In [31]: counts = get_counts(time_zones)
  2.  
  3. In [32]: counts['America/New_York']
  4. Out[32]: 1251
  5.  
  6. In [33]: len(time_zones)
  7. Out[33]: 3440

如果想要得到前10位的时区及其计数值,我们需要用到一些有关字典的处理技巧:

  1. def top_counts(count_dict, n=10):
  2. value_key_pairs = [(count, tz) for tz, count in count_dict.items()]
  3. value_key_pairs.sort()
  4. return value_key_pairs[-n:]

现在我们就可以:

  1. In [35]: top_counts(counts)
  2. Out[35]:
  3. [(33, u'America/Sao_Paulo'),
  4. (35, u'Europe/Madrid'),
  5. (36, u'Pacific/Honolulu'),
  6. (37, u'Asia/Tokyo'),
  7. (74, u'Europe/London'),
  8. (191, u'America/Denver'),
  9. (382, u'America/Los_Angeles'),
  10. (400, u'America/Chicago'),
  11. (521, u''),
  12. (1251, u'America/New_York')]

你可以在Python标准库中找到collections.Counter类,它能使这个任务变得更简单:

  1. In [49]: from collections import Counter
  2.  
  3. In [50]: counts = Counter(time_zones)
  4.  
  5. In [51]: counts.most_common(10)
  6. Out[51]:
  7. [(u'America/New_York', 1251),
  8. (u'', 521),
  9. (u'America/Chicago', 400),
  10. (u'America/Los_Angeles', 382),
  11. (u'America/Denver', 191),
  12. (u'Europe/London', 74),
  13. (u'Asia/Tokyo', 37),
  14. (u'Pacific/Honolulu', 36),
  15. (u'Europe/Madrid', 35),
  16. (u'America/Sao_Paulo', 33)]

用pandas对时区进行计数

DataFrame是pandas中最重要的数据结构,它用于将数据表示为一个表格。从一组原始记录中创建DataFrame是很简单的:

  1. In [289]: from pandas import DataFrame, Series
  2.  
  3. In [290]: import pandas as pd; import numpy as np
  4.  
  5. In [291]: frame = DataFrame(records)
  6.  
  7. In [292]: frame
  8. Out[292]:
  9. <class 'pandas.core.frame.DataFrame'>
  10. Int64Index: 3560 entries, 0 to 3559
  11. Data columns:
  12. _heartbeat_ 120 non-null values
  13. a 3440 non-null values
  14. al 3094 non-null values
  15. c 2919 non-null values
  16. cy 2919 non-null values
  17. g 3440 non-null values
  18. gr 2919 non-null values
  19. h 3440 non-null values
  20. hc 3440 non-null values
  21. hh 3440 non-null values
  22. kw 93 non-null values
  23. l 3440 non-null values
  24. ll 2919 non-null values
  25. nk 3440 non-null values
  26. r 3440 non-null values
  27. t 3440 non-null values
  28. tz 3440 non-null values
  29. u 3440 non-null values
  30. dtypes: float64(4), object(14)
  31.  
  32. In [293]: frame['tz'][:10]
  33. Out[293]:
  34. 0 America/New_York
  35. 1 America/Denver
  36. 2 America/New_York
  37. 3 America/Sao_Paulo
  38. 4 America/New_York
  39. 5 America/New_York
  40. 6 Europe/Warsaw
  41. 7
  42. 8
  43. 9
  44. Name: tz

这里frame的输出形式是摘要视图(summary view),主要用于较大的DataFrame对象。frame['tz']所返回的Series对象有一个value_counts方法,该方法可以让我们得到所需的信息:

  1. In [294]: tz_counts = frame['tz'].value_counts()
  2.  
  3. In [295]: tz_counts[:10]
  4. Out[295]:
  5. America/New_York 1251
  6. 521
  7. America/Chicago 400
  8. America/Los_Angeles 382
  9. America/Denver 191
  10. Europe/London 74
  11. Asia/Tokyo 37
  12. Pacific/Honolulu 36
  13. Europe/Madrid 35
  14. America/Sao_Paulo 33

然后,我们想利用绘图库(即matplotlib)为这段数据生成一张图片。为此,我们先给记录中未知或缺失的时区填上一个替代值。fillna函数可以替换缺失值(NA),而未知值(空字符串)则可以通过布尔型数组索引加以替换:

  1. In [296]: clean_tz = frame['tz'].fillna('Missing')
  2.  
  3. In [297]: clean_tz[clean_tz == ''] = 'Unknown'
  4.  
  5. In [298]: tz_counts = clean_tz.value_counts()
  6.  
  7. In [299]: tz_counts[:10]
  8. Out[299]:
  9. America/New_York 1251
  10. Unknown 521
  11. America/Chicago 400
  12. America/Los_Angeles 382
  13. America/Denver 191
  14. Missing 120
  15. Europe/London 74
  16. Asia/Tokyo 37
  17. Pacific/Honolulu 36
  18. Europe/Madrid 35

利用counts译注3对象的plot方法即可得到一张水平条形图译注4

  1. In [301]: tz_counts[:10].plot(kind='barh', rot=0)

最终结果如图2-1所示。我们还可以对这种数据进行很多处理。比如说,a字段含有执行URL短缩操作的浏览器、设备、应用程序的相关信息:

  1. In [302]: frame['a'][1]
  2. Out[302]: u'GoogleMaps/RochesterNY'
  3.  
  4. In [303]: frame['a'][50]
  5. Out[303]: u'Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2'
  6.  
  7. In [304]: frame['a'][51]
  8. Out[304]: u'Mozilla/5.0 (Linux; U; Android 2.2.2; en-us; LG-P925/V10e Build/FRG83G) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'

来自bit.ly的1.usa.gov数据 - 图1

图2-1:1.usa.gov示例数据中最常出现的时区

将这些"agent"字符串译注5中的所有信息都解析出来是一件挺郁闷的工作。不过只要你掌握了Python内置的字符串函数和正则表达式,事情就好办了。比如说,我们可以将这种字符串的第一节(与浏览器大致对应)分离出来并得到另外一份用户行为摘要:

  1. In [305]: results = Series([x.split()[0] for x in frame.a.dropna()])
  2.  
  3. In [306]: results[:5]
  4. Out[306]:
  5. 0 Mozilla/5.0
  6. 1 GoogleMaps/RochesterNY
  7. 2 Mozilla/4.0
  8. 3 Mozilla/5.0
  9. 4 Mozilla/5.0
  10.  
  11. In [307]: results.value_counts()[:8]
  12. Out[307]:
  13. Mozilla/5.0 2594
  14. Mozilla/4.0 601
  15. GoogleMaps/RochesterNY 121
  16. Opera/9.80 34
  17. TEST_INTERNET_AGENT 24
  18. GoogleProducer 21
  19. Mozilla/6.0 5
  20. BlackBerry8520/5.0.0.681 4

现在,假设你想按Windows和非Windows用户对时区统计信息进行分解。为了简单起见,我们假定只要agent字符串中含有"Windows"就认为该用户为Windows用户。由于有的agent缺失,所以首先将它们从数据中移除:

  1. In [308]: cframe = frame[frame.a.notnull()]

其次根据a值计算出各行是否是Windows:

  1. In [309]: operating_system = np.where(cframe['a'].str.contains('Windows'),
  2. ...: 'Windows', 'Not Windows')
  3.  
  4. In [310]: operating_system[:5]
  5. Out[310]:
  6. 0 Windows
  7. 1 Not Windows
  8. 2 Windows
  9. 3 Not Windows
  10. 4 Windows
  11. Name: a

接下来就可以根据时区和新得到的操作系统列表对数据进行分组了:

  1. In [311]: by_tz_os = cframe.groupby(['tz', operating_system])

然后通过size对分组结果进行计数(类似于上面的value_counts函数),并利用unstack对计数结果进行重塑:

  1. In [312]: agg_counts = by_tz_os.size().unstack().fillna(0)
  2.  
  3. In [313]: agg_counts[:10]
  4. Out[313]:
  5. a Not Windows Windows
  6. tz
  7. 245 276
  8. Africa/Cairo 0 3
  9. Africa/Casablanca 0 1
  10. Africa/Ceuta 0 2
  11. Africa/Johannesburg 0 1
  12. Africa/Lusaka 0 1
  13. America/Anchorage 4 1
  14. America/Argentina/Buenos_Aires 1 0
  15. America/Argentina/Cordoba 0 1
  16. America/Argentina/Mendoza 0 1

最后,我们来选取最常出现的时区。为了达到这个目的,我根据agg_counts中的行数构造了一个间接索引数组:

  1. # 用于按升序排列
  2. In [314]: indexer = agg_counts.sum(1).argsort()
  3.  
  4. In [315]: indexer[:10]
  5. Out[315]:
  6. tz
  7. 24
  8. Africa/Cairo 20
  9. Africa/Casablanca 21
  10. Africa/Ceuta 92
  11. Africa/Johannesburg 87
  12. Africa/Lusaka 53
  13. America/Anchorage 54
  14. America/Argentina/Buenos_Aires 57
  15. America/Argentina/Cordoba 26
  16. America/Argentina/Mendoza 55

然后我通过take按照这个顺序截取了最后10行:

  1. In [316]: count_subset = agg_counts.take(indexer)[-10:]
  2.  
  3. In [317]: count_subset
  4. Out[317]:
  5. a Not Windows Windows
  6. tz
  7. America/Sao_Paulo 13 20
  8. Europe/Madrid 16 19
  9. Pacific/Honolulu 0 36
  10. Asia/Tokyo 2 35
  11. Europe/London 43 31
  12. America/Denver 132 59
  13. America/Los_Angeles 130 252
  14. America/Chicago 115 285
  15. 245 276
  16. America/New_York 339 912

这里也可以生成一张条形图。我将使用stacked=True来生成一张堆积条形图(如图2-2所示):

  1. In [319]: count_subset.plot(kind='barh', stacked=True)

由于在这张图中不太容易看清楚较小分组中Windows用户的相对比例,因此我们可以将各行规范化为“总计为1”并重新绘图(如图2-3所示):

  1. In [321]: normed_subset = count_subset.div(count_subset.sum(1), axis=0)
  2. In [322]: normed_subset.plot(kind='barh', stacked=True)

这里所用到的所有方法都会在本书后续的章节中详细讲解。

译注1:由于可以通过短链接伪造.gov后缀的URL,导致用户访问恶意域名,所以美国政府开始着手处理这种事情了。

译注2:以Feed形式提供。

注1:网址:http://www.usa.gov/About/developer-resources/1usagov.shtml。

译注3:应该是tz_counts 。

译注4:注意,一定要以pylab模式打开,否则这条代码没效果。包括很多缩写,pylab都直接弄好了,如果不是用这种模式打开,后面很多代码一样会遇到问题,虽然不是什么大毛病,但毕竟麻烦。后面如果遇到这没定义那找不到的情况,就请注意是不是因为这个。

译注5:即浏览器的USER_AGENT信息。