ch02
’本书将要向你介绍的是用于高效处理数据的Python工具。虽然读者各自工作的最终目的千差万别,但基本上都需要完成一下几个大类的任务:
与外界进行交互
准备
转换
建模和计算
展示
内容提要
- 从txt读入json格式数据,转化为字典
- 使用Python字典函数对字典中某一特定元素进行计数
- 绘制柱状图,并运用不同柱状图体现每一类型的组成及其比例
读入数据
path = 'C:/.../usagov_bitly_data2012-03-16-1331923249.txt'#location of file
open(path).readline()
这样读入数据的第一行
数据可以从这本书的git链接上获取https://github.com/wesm/pydata-book/tree/1st-edition/ch02
open(path).readlines()
这样读入所有的数据,并将数据存放在列表里,以换行符为分割的依据
import json
records = [json.loads(line) for line in open(path)]
由于数据是json格式的字符串,使用json包可以方便地将其(每一行)转化为Python字典对象,具体实现方法是列表推导
print('records[0]', records[0],'\n')
print('records[0][\'tz\']', records[0]['tz'],'\n')
访问数据具体的元素
用Python代码对时区进行计数
time_zones = [rec['tz'] for rec in records if 'tz' in rec]
time_zones = [rec['tz'] for rec in records ]
采用前一种的原因是,并不是每一个元素都有名为’tz’的项,否则出现以下错误KeyError: 'tz'
from collections import Counter
counts = Counter(time_zones)
print(counts.most_common(10))
对字典中的元素计数,较为推荐的是采用Python标准库里面的Counter函数,如上;当然也可以自己写函数,如下:
def get_counts(sequence):#using a dict to get the time of occurrance is a good way
counts={}
for x in sequence:
if x in counts:
counts[x] += 1
else:
counts[x] = 1
return counts
counts = get_counts(time_zones)
def top_counts(count_dict, n=10):
value_key_pairs = [(count, tz) for tz, count in count_dict.items()]
value_key_pairs.sort()
return value_key_pairs[-n:]
print('top_counts(counts)', top_counts(counts))
用Pandas对时区进行计数
from pandas import DataFrame, Series
import pandas as pd; import numpy as np
frame = DataFrame(records)
frame['tz'][:10]
这里frame的输出形式是摘要视图(summary view),主要用于比较大的DataFrame对象,frame[‘tz’]所返回的Series对象有一个value_counts方法,可以让我们获得需要的信息
tz_counts = frame['tz'].value_counts()
画图
clean_tz = frame['tz'].fillna('Missing')
clean_tz[clean_tz == ''] = 'Unknown'
tz_counts = clean_tz.value_counts()
使用fillna函数替换缺失值(NA),用’Unknown’替换空字符串
tz_counts[:10].plot(kind='barh',rot=0)
相似的方法处理不同的浏览器
results = Series([x.split()[0] for x in frame.a.dropna()])
cframe = frame[frame.a.notnull()]
operating_system = np.where(cframe['a'].str.contains('Windows'), 'Windows', 'Not Windows')
先去除缺失的值,获得cframe,再通过where函数添加os信息
by_tz_os = cframe.groupby(['tz', operating_system])
基于operating_system进行分组
agg_counts = by_tz_os.size().unstack().fillna(0)
用size函数进行计数,并利用unstack对计数结果进行重塑
indexer = agg_counts.sum(1).argsort()
count_subset = agg_counts.take(indexer)[-10:]
count_subset.plot(kind='barh', stacked = True)
normed_subset = count_subset.div(count_subset.sum(1), axis = 0)
normed_subset.plot(kind='barh', stacked=True)
进行相对比例的比较展示
Never mind happiness, do your mission.