【发布时间】:2018-09-09 06:37:19
【问题描述】:
我有一个大型的商业物业地址数据库(大约 500 万行),其中 200,000 个缺少楼面面积。这些房产是按行业分类的,我知道每个房产的租金。
我对缺失的建筑面积进行插值的方法是在建筑面积未知的房产的指定半径内过滤出类似分类的房产,然后根据附近房产的成本/平方米的中位数计算建筑面积。
最初,我使用pandas 来解决这个问题,但随着数据集变得越来越大(即使使用group_by),这已经成为问题。它经常超出可用内存并停止。当它工作时,大约需要 3 个小时才能完成。
我正在测试是否可以在数据库中执行相同的任务。我为径向填充编写的函数如下:
def _radial_fill(self):
# Initial query selecting all latest locations, and excluding null rental valuations
q = Location.objects.order_by("locode","-update_cycle") \
.distinct("locode")
# Chained Q objects to use in filter
f = Q(rental_valuation__isnull=False) & \
Q(use_category__grouped_by__isnull=False) & \
Q(pc__isnull=False)
# All property categories at subgroup level
for c in LocationCategory.objects.filter(use_category="SGP").all():
# Start looking for appropriate interpolation locations
fc = f & Q(use_category__grouped_by=c)
for l in q.filter(fc & Q(floor_area__isnull=True)).all():
r_degree = 0
while True:
# Default Distance is metres, so multiply accordingly
r = (constants.BOUNDS**r_degree)*1000 # metres
ql = q.annotate(distance=Distance("pc__point", l.pc.point)) \
.filter(fc & Q(floor_area__isnull=False) & Q(distance__lte=r)) \
.values("rental_valuation", "floor_area")
if len(ql) < constants.LOWER_RANGE:
if r > constants.UPPER_RADIUS*1000:
# Further than the longest possible distance
break
r_degree += 1
else:
m = median([x["rental_valuation"]/x["floor_area"]
for x in ql if x["floor_area"] > 0.0])
l.floor_area = l.rental_valuation / m
l.save()
break
我的问题是这个函数需要 6 天才能运行。必须有更快的方法,对吧?我确定我做错了什么......
型号如下:
class LocationCategory(models.Model):
# Category types
GRP = "GRP"
SGP = "SGP"
UST = "UST"
CATEGORIES = (
(GRP, "Group"),
(SGP, "Sub-group"),
(UST, "Use type"),
)
slug = models.CharField(max_length=24, primary_key=True, unique=True)
usecode = models.CharField(max_length=14, db_index=True)
use_category = models.CharField(max_length=3, choices=CATEGORIES,
db_index=True, default=UST)
grouped_by = models.ForeignKey("self", null=True, blank=True,
on_delete=models.SET_NULL,
related_name="category_by_group")
class Location(models.Model):
# Hereditament identity and location
slug = models.CharField(max_length=24, db_index=True)
locode = models.CharField(max_length=14, db_index=True)
pc = models.ForeignKey(Postcode, null=True, blank=True,
on_delete=models.SET_NULL,
related_name="locations_by_pc")
use_category = models.ForeignKey(LocationCategory, null=True, blank=True,
on_delete=models.SET_NULL,
related_name="locations_by_category")
# History fields
update_cycle = models.CharField(max_length=14, db_index=True)
# Location-specific econometric data
floor_area = models.FloatField(blank=True, null=True)
rental_valuation = models.FloatField(blank=True, null=True)
class Postcode(models.Model):
pc = models.CharField(max_length=7, primary_key=True, unique=True) # Postcode excl space
pcs = models.CharField(max_length=8, unique=True) # Postcode incl space
# http://spatialreference.org/ref/epsg/osgb-1936-british-national-grid/
point = models.PointField(srid=4326)
使用 Django 2.0 和 Postgresql 10
更新
通过以下代码更改,我在运行时实现了 35% 的改进:
# Initial query selecting all latest locations, and excluding null rental valuations
q = Location.objects.order_by("slug","-update_cycle") \
.distinct("slug")
# Chained Q objects to use in filter
f = Q(rental_valuation__isnull=False) & \
Q(pc__isnull=False) & \
Q(use_category__grouped_by_id=category_id)
# All property categories at subgroup level
# Start looking for appropriate interpolation locations
for l in q.filter(f & Q(floor_area__isnull=True)).all().iterator():
r = q.filter(f & Q(floor_area__isnull=False) & ~Q(floor_area=0.0))
rl = Location.objects.filter(id__in = r).annotate(distance=D("pc__point", l.pc.point)) \
.order_by("distance")[:constants.LOWER_RANGE] \
.annotate(floor_ratio = F("rental_valuation")/
F("floor_area")) \
.values("floor_ratio")
if len(rl) == constants.LOWER_RANGE:
m = median([h["floor_ratio"] for h in rl])
l.floor_area = l.rental_valuation / m
l.save()
id__in=r 效率低下,但它似乎是在对新注释添加和排序时维护distinct 查询集的唯一方法。鉴于在 r 查询中可以返回大约 100,000 行,因此在此处应用的任何注释以及随后按距离排序都可能需要很长时间。
但是……我在尝试实现子查询功能时遇到了很多问题。 AttributeError: 'ResolvedOuterRef' object has no attribute '_output_field_or_none' 我认为与注释有关,但我找不到太多。
相关重构代码为:
rl = Location.objects.filter(id__in = r).annotate(distance=D("pc__point", OuterRef('pc__point'))) \
.order_by("distance")[:constants.LOWER_RANGE] \
.annotate(floor_ratio = F("rental_valuation")/
F("floor_area")) \
.distinct("floor_ratio")
和:
l.update(floor_area= F("rental_valuation") / CustomAVG(Subquery(locs),0))
我可以看到这种方法应该非常有效,但要做到正确似乎有点超出我的技能水平。
【问题讨论】:
标签: python django postgresql pandas geodjango