Skip to content

Commit 9644219

Browse files
authoredNov 11, 2024··
Merge pull request #2554 from thejud/window_function_guide
[guide] Add a WindowFunctionGuide
2 parents 59344b6 + a350912 commit 9644219

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
 
+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
---
2+
sheet: Sheet
3+
---
4+
# Create a window over consecutive rows
5+
6+
Window functions enable computations that relate the current window to surrounding rows, like cumulative sum, rolling averages or lead/lag computations.
7+
8+
{help.commands.addcol-window}
9+
10+
With large window sizes, [:code]g'[/] (`freeze-sheet`) to calculate all cells and copy the entire sheet into a new source sheet, which will conserve CPU.
11+
12+
## Examples
13+
14+
date color price
15+
---------- ----- -----
16+
2024-09-01 R 30
17+
2024-09-02 B 28
18+
2024-09-03 R 100
19+
2024-09-03 B 33
20+
2024-09-03 B 99
21+
22+
23+
1. [:keys]#[/] (`type-int`) on the **price** column to type as int.
24+
2. [:keys]w[/] (`addcol-window`) on the **price** column, followed by `1 2`, to create a window consisting of 4 rows: 1 row before the current row, and 2 rows after.
25+
3. To create a moving average of the values in the window, add a new column with a python expression: [:keys]=[/] (`addcol-expr`)
26+
followed by `sum(price_window)/len(price_window)`
27+
28+
date color price price_window sum(price_window)/len(price_window)
29+
---------- ----- ----- ------------------- -----------------------------------
30+
2024-09-01 R 38 [4] ; 38; 28; 100 41.5
31+
2024-09-02 B 28 [4] 38; 28; 100; 33 49.75
32+
2024-09-03 R 100 [4] 28; 100; 33; 99 65.0
33+
2024-09-03 B 33 [4] 100; 33; 99; 58.0
34+
2024-09-03 B 99 [4] 33; 99; ; 33.0
35+
36+
37+
## Workflows
38+
39+
### Create a cumulative sum
40+
41+
1. Set the before window size to the total number of rows in the table, and the after rows to 0. In the above example that would be `w 5 0` (`addcol-window`).
42+
2. Add an expression ([:keys]=[/] (`addcol-expr`) of `sum(window)` where `window` is the name of the window function column.
43+
44+
### Compute the change between rows
45+
46+
1. `w 1 0` on the `foo` column to create a window function of size 1 before and 0 after.
47+
2. Add a python expression. The window function column is 'foo_window':
48+
`=foo_window[1] - foo_window[0] if len(foo_window) > 1 else None`
49+

0 commit comments

Comments
 (0)
Please sign in to comment.