Skip to content

Window functions over groups #3

Closed

Description

@culebron

I've worked with SQL a lot and now already 5 years with Pandas, and sometimes both drive me absolutely mad. In some aspects Pandas in Python is nicer, but things like window functions are absolutely horrible.

Example:

orders
------
cell   (a cell on a map)
hour   (datetime but rounded to hours)
amount

with some calculations we should produce this:

orders
------
cell
hour_index (unix timestamp // 3600)
hour
day_of_year
day_of_week
week_of_year
year

And then for each row, calculate

  1. A = orders for the same day of week and same hour for the previous 10 weeks.
  2. B = calculate mean orders per whole day for the same days of week for the previous 10 weeks.
  3. C = calculate total orders yesterday.
  4. A * C / B

I've done only part 1 in Pandas, and it's awful.

dc = data.copy()
data['mean_orders'] = 0
for i in tqdm(range(1, 11)):
    dc.week += 1
    data = data.merge(dc[['cell', 'week', 'weekday', 'orders']], on=['cell', 'weekday', 'week'], suffixes=('', '_other'))
    data['mean_orders'] += data['orders_other'] / 10
    data.drop('orders_other', inplace=True, axis=1)

I can think of PostgreSQL equivalent (though window function names and params might not be exactly these):

select cell, first(orders),
    sum(orders, 10) over (partition by cell, day_of_week, hour order by week) / 10 mean_same_hour_over_week,
    sum(orders, 168) over (partition by cell order by hour) / 7 mean_per_day_over_week,
    sum(b.orders)
from orders a inner join orders y on y.hour_index between (a.hour_index - a.hour) and (a.hour_index - a.hour - 24)
group by cell, orders;

...and then put it into a CTE and do the multiplication & division.

Activity

  1. aljazerzen commented on Apr 12, 2022

    @aljazerzen
    Member

    So looking at this, I don't understand what you are doing with pandas.

    The SQL query may not be correct, because for each cell, you are averaging within whole partitions, not just last 10 weeks.

    Using your description of the problem and latest language proposals, the PRQL solution would be:

    table by_day = (
      from cells
      select [cell, datetime, amount]  # this is here just to give a hint about the frame
      derive day: s"date_trunc('day', datetime)"
      aggregate by:[cell, day] [sum_day: sum amount]
    )
    
    from cells
    select [cell, datetime, amount]
    derive [
      day: s"date_trunc('day', datetime)",
      dow: s"EXTRACT(DOW FROM datetime)", # day of the week
      hour: s"EXTRACT(HOUR FROM datetime)",
    ]
    sort datetime
    compute by:[cell, dow, hour] rows:-241..-1 [ # 240 preceeding rows, up to current row
      mean_dow_hour: average amount
    ]
    compute by:[cell, dow] rows:-11..-1 [ # 10 preceeding rows, up to current row
      mean_dow: average amount
    ]
    join yesterday:by_day [
      by_day.day = $.day - s"interval 1 day",
    ]
    select [
      cell, 
      datetime,
      amount,
      yesterday.sum_day * mean_dow_hour / mean_dow
    ]

    Note that currently, compute is not implemented, but it would represent windowing operation. Also, range is specified using not yet implemented x..y operator.

    @culebron is this readable? Does it do what you wanted?

  2. added
    language-design
    and removed on Apr 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    language-design

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions