這個(gè)案例主要目的是轉(zhuǎn)換json類(lèi)型的數(shù)據(jù)霉猛,利用python和pandas方法進(jìn)行計(jì)數(shù)印蔗。
step1:獲取數(shù)據(jù)
將json格式數(shù)據(jù)轉(zhuǎn)化成python對(duì)象
import json
path=r'D:\datasets\bitly_usagov\example.txt'#寫(xiě)自己的路徑
records=[json.loads(line) for line in open(path,encoding='utf8')]
#小tips:json.load和json.loads的都是將json轉(zhuǎn)換成python
#區(qū)別是:引用:https://zhuanlan.zhihu.com/p/373661877
records數(shù)據(jù).png
step2純python時(shí)區(qū)計(jì)數(shù)
1.獲取時(shí)區(qū)+計(jì)數(shù)
time_zones=[rec['tz'] for rec in records if 'tz' in rec]#不進(jìn)行判斷則會(huì)遇到中斷報(bào)錯(cuò)
#遍歷時(shí)區(qū)使用字典進(jìn)行存儲(chǔ)計(jì)數(shù)
def get_counts(sequence):
counts={}
for x in sequence:
if x in counts:
counts[x]+=1
else:
counts[x]=1
return counts
#利用python中的高級(jí)工具,可以讓過(guò)程更簡(jiǎn)潔
from collections import defaultdict
def getcounts2(sequence):
counts=defaultdict(int)#初始值為1游昼,格式為字典
for x in sequence:
counts[x]+=1
return counts
#應(yīng)用函數(shù)
counts=get_counts(time_zones)
#看某個(gè)時(shí)區(qū)的計(jì)數(shù)是多少
counts['American/New_York']
2.對(duì)以上字典形式進(jìn)行計(jì)數(shù)
#定義一個(gè)排序函數(shù)是牢,得到排序前10的時(shí)區(qū)
def top_counts(count_dict,n=10):
value_key_pairs=[(count,tz) for tz,count in count_dict.items()]#items()表示字典的key+values
value_key_pairs.sort()#默認(rèn)對(duì)值進(jìn)行排序
return value_key_pairs[-n:]
top_counts(counts)
3.更更簡(jiǎn)單的方法斯稳,直接用python標(biāo)準(zhǔn)庫(kù)的collections.Counters類(lèi)
從僅獲取時(shí)區(qū)后開(kāi)始
from collections import Counter
counts=Counter(time_zones)#以字典形式存儲(chǔ)計(jì)數(shù)
counts.most_commom(10)#由高到低排列
時(shí)區(qū)排序.png
step3 使用pandas計(jì)數(shù)
#使用value_counts()函數(shù)進(jìn)行計(jì)數(shù)
import pandas as pd
frame=pd.DataFrame(records)#相當(dāng)于把字典的每個(gè)Key作為列標(biāo)簽
tz_counts=frame['tz'].value_counts()#直接使用value_counts()函數(shù)進(jìn)行計(jì)數(shù)
tz_counts[:10]#選取前10名
#缺失值進(jìn)行填充
clean_tz=frame['tz'].fillna('Missing')
clean_tz[clean_tz==' ']='unknow'#按條件獲取值
step4 可視化 seaborn
import seaborn as sns
sns.barplot(y=subset.index,x=subset.values)#barplot柱狀圖 catplot 散點(diǎn)圖
5.補(bǔ)充一些語(yǔ)句
#類(lèi)似if的語(yǔ)句
np.where(條件,條件為真時(shí)的值,條件為假時(shí)的值)
#某個(gè)字段是否有某值
frame['a'].str.contains('w')#判斷a列的值里面是否有‘w’字
#分組計(jì)數(shù)(grouoby)時(shí)用size()
#列標(biāo)簽變成一欄
data.reset_index()