我尝试使用用于直方图的价格计数来创建垃圾箱。 我希望垃圾箱为0-1000,1000-2000,2000-3000等等。如果我只是按照我的方式进行分组,我可以使用许多不同的箱子。
我写的代码似乎以无限循环结束(或者至少脚本在一小时后仍在运行)。我不确定如何正确地做到这一点。这是我写的代码:
from itertools import zip_longest
def price_histogram(area_id, agency_id):
# Get prices and total count for competitors
query = HousePrice.objects.filter(area_id=area_id, cur_price__range=(1000,30000)).exclude(agency_id=agency_id)
count = query.values('cur_price').annotate(count=Count('cur_price')).order_by('cur_price')
total = query.count()
# Get prices and total count for selected agency
query_agency = HousePrice.objects.filter(area_id=area_id, agency_id=agency_id, cur_price__range=(1000,30000))
count_agency = query_agency.values('cur_price').annotate(count=Count('cur_price')).order_by('cur_price')
total_agency = query_agency.count()
# Make list for x and y values
x_comp = []
y_comp = []
x_agency = []
y_agency = []
bin_start = 0
bin_end = 1000
_count_comp = 0
_count_agency = 0
for row_comp, row_agency in zip_longest(count, count_agency, fillvalue={}):
while bin_start < int(row_comp['cur_price']) < bin_end:
_count_comp += row_comp['count']
_count_agency += row_agency.get('count', 0)
bin_start += 1000
bin_end += 1000
x_comp.append(str(bin_start) + "-" + str(bin_end) + " USD")
x_agency.append(str(bin_start) + "-" + str(bin_end) + " USD")
y_comp.append(_count_comp/total)
y_agency.append(_count_agency/total_agency)
return {'x_comp': x_comp, 'y_comp': y_comp, 'x_agency': x_agency, 'y_agency': y_agency}
我使用的是Python 3.5和Django 1.10。
答案 0 :(得分:0)
我来晚了一点,但是也许django-pivot库可以满足您的要求。
from django_pivot.histogram import histogram
query = HousePrice.objects.filter(area_id=area_id, cur_price__range=(1000,30000)).exclude(agency_id=agency_id
hist = histogram(query, cur_price, bins=[1000:30000:1000])