# 【利用python进行数据分析】准备与实例（一）

• 与外界进行交互，读写各种各样的文件格式和数据库
• 准备，对数据进行清理、修整、整合、规范化、重塑、切片切块、变形等处理以便进行分析
• 转换，对数据集做一些数学和统计运算，以产生新的数据集。比如说，根据分组变量对一个大表进行聚合
• 建模和计算，将数据跟统计模型、机器学习算法或其他计算工具联系起来
• 展示，创建交互式的或静态的图片或文字摘要

path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'


'{ "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'

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

records[0]
records[0]['tz']


{'a': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.78 Safari/535.11',
'al': 'en-US,en;q=0.8',
'c': 'US',
'cy': 'Danvers',
'g': 'A6qOVH',
'gr': 'MA',
'h': 'wfLQtf',
'hc': 1331822918,
'hh': '1.usa.gov',
'l': 'orofrog',
'll': [42.576698, -70.954903],
'nk': 1,
't': 1331923247,
'tz': 'America/New_York',
'u': 'http://www.ncbi.nlm.nih.gov/pubmed/22415991'}
'America/New_York'

from pandas import DataFrame
import json
path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
records = [json.loads(line) for line in open(path)]
frame=DataFrame(records)
tz_counts=frame['tz'].value_counts()
#print(tz_counts[:10])

#以下是对空缺值的清洗
clean_tz=frame['tz'].fillna(value='Missing')
clean_tz[clean_tz ==''] = 'Unknown'
tz_counts=clean_tz.value_counts()
print(tz_counts[:10])

America/New_York       1251
Unknown                 521
America/Chicago         400
America/Los_Angeles     382
America/Denver          191
Missing                 120
Europe/London            74
Asia/Tokyo               37
Pacific/Honolulu         36
Name: tz, dtype: int64


from matplotlib import pyplot as plt
tz_counts[:10].plot(kind='barh',rot=0)
plt.show()

from pandas import DataFrame,Series
from matplotlib import pyplot as plt
import json
path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
records = [json.loads(line) for line in open(path)]
frame=DataFrame(records)
results=Series([x.split()[0] for x in frame.a.dropna()])
print(results.value_counts()[:8])

Mozilla/5.0                 2594
Mozilla/4.0                  601
Opera/9.80                    34
TEST_INTERNET_AGENT           24
Mozilla/6.0                    5
BlackBerry8520/5.0.0.681       4
dtype: int64

res_cnt=results.value_counts()[:8]
res_cnt.plot(kind='barh',rot=0)
plt.show()

from pandas import DataFrame,Series
from matplotlib import pyplot as plt
import json
path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
records = [json.loads(line) for line in open(path)]
frame=DataFrame(records)
cframe=frame[frame.a.notnull()]
# print(cframe.groupby('tz').size())   发现tz分组后，有521类
operating_system=np.where(cframe['a'].str.contains('Windows'),'Windows','Not Windows')
cframe['a']=DataFrame(operating_system)
by_tz_os=cframe.groupby(['tz','a'])
agg_counts=by_tz_os.size().unstack().fillna(0)   #用unstack将行转换成列
print(agg_counts[:10])


a                               Not Windows  Windows
tz
180.0    316.0
Africa/Cairo                            1.0      2.0
Africa/Casablanca                       0.0      1.0
Africa/Ceuta                            1.0      1.0
Africa/Johannesburg                     0.0      1.0
Africa/Lusaka                           1.0      0.0
America/Anchorage                       0.0      4.0
America/Argentina/Buenos_Aires          0.0      1.0
America/Argentina/Cordoba               1.0      0.0
America/Argentina/Mendoza               0.0      1.0

#用于按升序排列
indexer = agg_counts.sum(1).argsort()
#通过take按照这个顺序截取了最后10行
count_subset = agg_counts.take(indexer)[-10:]
print(count_subset)

a                    Not Windows  Windows
tz
America/Sao_Paulo           12.0     21.0
Pacific/Honolulu            10.0     25.0
Asia/Tokyo                  14.0     23.0
Europe/London               32.0     40.0
America/Denver              56.0    125.0
America/Los_Angeles        122.0    247.0
America/Chicago            131.0    249.0
180.0    316.0
America/New_York           426.0    798.0

count_subset.plot(kind='barh',stacked=True)
plt.show()