从Django查询创建直方图箱

问题描述 投票:1回答:1

我正在尝试创建用于直方图的价格计数的箱子。我希望垃圾箱为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。

python django python-3.x
1个回答
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])
© www.soinside.com 2019 - 2024. All rights reserved.