# -*- coding: utf-8 -*-
import json
path = '/home/wsx/文檔/pydata-book-master/ch02/usagov_bitly_data2012-03-16-1331923249.txt'
records = [json.loads(line) for line in open(path)]
time_zones = [rec['tz'] for rec in records if 'tz' in rec]
#計數(shù)
#1
def get_counts(sequence):
counts = {}
for x in sequence:
if x in counts:
counts[x] += 1
else:
counts[x] = 1
return counts
#2
from collections import defaultdict
def get_counts2(sequence):
counts = defaultdict(int) #所有的值均會被初始化為0
for x in sequence:
counts[x] += 1
return counts
counts = get_counts(time_zones)
#得到前10位的時區(qū)及其計數(shù)值
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:]
#可以在Python標準庫中找到collection.Counter類,它能使這個任務變得更簡單
from collections import Counter
counts = Counter(time_zones)
counts.most_common(10)
#用pandas對時區(qū)進行計數(shù)
from pandas import DataFrame, Series
import pandas as pd; import numpy as np
frame = DataFrame(records)
frame
tz_counts = frame['tz'].value_counts()
tz_counts[:10]
#然后,我們想利用繪圖庫(matplotlib)為這段數(shù)據(jù)生成一張圖片。為此,我們先給記錄中未知
#或者缺失的時區(qū)填上一個替代值。fillna函數(shù)可以替換缺失值,而未知值可以通過布爾型數(shù)組
#索引加以替換:
clean_tz = frame['tz'].fillna('Missing')
clean_tz[clean_tz == ''] = 'Unkonwn'
tz_counts = clean_tz.value_counts()
tz_counts[:10]
tz_counts[:10].plot(kind='barh', rot=0)
利用Ipython進行計數(shù)和畫圖
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。