Binning

Binning Timestamps

Timestamps can be binned into days, weeks, months, etc. using attr.your_timestamp.by_<granularity>.

This can be used to quickly hashquery.Model.aggregate() data into timestamp bins:

yearly_sales = (
  demo_project.models.sales
  .aggregate(
    groups=[attr.timestamp.by_year],
    measures=[msr.revenue],
  )
  .sort(attr.timestamp)
)

Binning Numerics

Note

In future, Hashquery will provide ColumnExpression.binned to achieve this behavior more easily.

You can write your own binning manually using func.cases.

sales_binned_by_price = (
  demo_project.models.sales
  .aggregate(
    groups=[func.cases(
      func.cases(
        ((attr.item_price > 0 & attr.item_price < 10), "0-10"),
        ((attr.item_price >= 10 & attr.item_price < 20), "10-20"),
        other="30+",
      )
    )],
    measures=[msr.count],
  )
)