最近一直忙于工作,作业现在才交,实在不好意思。
根据赶集网北京二手市场数据源,统计两个数据项
1. 北京是各城区发帖量最多的TOP3商品类目
2. 各大类目中各成色对应的平均价位
代码如下:
#coding=utf-8
import pymongo
import charts
client = pymongo.MongoClient('localhost', 27017)
db = client['ganji']
items_collection = db['item_info']
def get_areas():
"""获得所有的城区的名字"""
pipeline = [
{'$group': {'_id': {'$slice': ['$area', 1]}}}
]
areas = [info['_id'][0] for info in items_collection.aggregate((pipeline))]
return areas
def get_top3(area):
"""获得指定城区的发帖量前三的类目,以及发帖量"""
pipeline2 = [
{'$match': {'area': area}},
{'$group': {'_id': {'$slice': ['$cates', 2, 1]}, 'counts': {'$sum': 1}}},
{'$sort': {'counts': -1}},
{'$limit': 3}
]
info = [{'name':info['_id'][0],'data':[info['counts']],'type':'column'}
for info in items_collection.aggregate(pipeline2)]
return info
#选择一个城区,在notebook中展示发帖量统计
areas = get_areas()
series = get_top3(areas[0])
options = {
'title': {'text': '发帖量统计'},
'subtitle': {'text': str(areas[0].encode('utf-8')) + '城区发帖量TOP3'}
}
charts.plot(series,options,show='inline')
效果如下:
image.png
各大类目中各成色对应的平均价位
def get_cates():
"""获得所有的类目名称"""
pipeline = [
{'$group':{'_id':{'$slice':['$cates',2,1]}}}
]
return [cate['_id'][0] for cate in items_collection.aggregate(pipeline)]
def get_avg_price(cate):
""" 在这里需要对成色进行一下转换,因为数据库里面成色信息是字符串,不好进行排序,因为我们需要按照 成色信息按照从全新到报废进行排序"""
def zhuanhuan_chengse(chengse,info):
"""成色转换"""
data = {
u'全新':{'chengse':100,'info':info['counts'],'cate':info['_id']},
u'99成新':{'chengse':99,'info':info['counts'],'cate':info['_id']},
u'95成新':{'chengse':95,'info':info['counts'],'cate':info['_id']},
u'9成新':{'chengse':90,'info':info['counts'],'cate':info['_id']},
u'8成新':{'chengse':80,'info':info['counts'],'cate':info['_id']},
u'7成新及以下':{'chengse':70,'info':info['counts'],'cate':info['_id']},
u'报废机/尸体':{'chengse':0,'info':info['counts'],'cate':info['_id']},
}
return data.get(chengse,'None')
pipeline = [
{'$match': {'look': {'$ne': '-'},'cates':cate}},
{'$group': {'_id': '$look', 'counts': {'$avg': '$price'}}},
]
infos = sorted([zhuanhuan_chengse(info['_id'],info)
for info in items_collection.aggregate(pipeline)],key=lambda x:x['chengse'],reverse=True)
return [info['info'] for info in infos],[info['cate'] for info in infos]
#选取其中第一个类目
cates = get_cates()
cate = cates[0]
date = get_avg_price(cate)
serice = [{
'name':cate,
'data':date[0]
}]
options = {
'title': {'text': '成色平均价格统计'},
'subtitle': {'text': str(cate.encode('utf-8')) + '类目成色价格平均统计'},
'xAxis':{'categories':date[1],'title':{'text':'价格'}}
}
charts.plot(serice,options,show='inline')
效果如下:
image.png
网友评论