Repository navigation
Closed
Labels
language-designChanges to PRQL-the-language
Description
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
- A = orders for the same day of week and same hour for the previous 10 weeks.
- B = calculate mean orders per whole day for the same days of week for the previous 10 weeks.
- C = calculate total orders yesterday.
- 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.
Metadata
Metadata
Assignees
Labels
language-designChanges to PRQL-the-language
Activity
aljazerzen commentedon Apr 12, 2022
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:
Note that currently,
computeis not implemented, but it would represent windowing operation. Also, range is specified using not yet implementedx..yoperator.@culebron is this readable? Does it do what you wanted?