with_groups
In [1]:
Copied!
# https://dplyr.tidyverse.org/reference/with_groups.html
%run nb_helpers.py
from datar.all import *
nb_header(with_groups)
# https://dplyr.tidyverse.org/reference/with_groups.html
%run nb_helpers.py
from datar.all import *
nb_header(with_groups)
In [2]:
Copied!
df = tibble(g=c(1, 1, 2, 2, 3), x=runif(5))
df >> with_groups(f.g, mutate, x_mean = mean(f.x))
df = tibble(g=c(1, 1, 2, 2, 3), x=runif(5))
df >> with_groups(f.g, mutate, x_mean = mean(f.x))
Out[2]:
g | x | x_mean | |
---|---|---|---|
<int64> | <float64> | <float64> | |
0 | 1 | 0.244611 | 0.525006 |
1 | 1 | 0.805402 | 0.525006 |
2 | 2 | 0.862707 | 0.829213 |
3 | 2 | 0.795719 | 0.829213 |
4 | 3 | 0.812910 | 0.812910 |
TibbleGrouped: g (n=3)
In [3]:
Copied!
df >> with_groups(f.g, lambda df: df >> mutate(x1 = first(f.x)))
df >> with_groups(f.g, lambda df: df >> mutate(x1 = first(f.x)))
Out[3]:
g | x | x1 | |
---|---|---|---|
<int64> | <float64> | <float64> | |
0 | 1 | 0.244611 | 0.244611 |
1 | 1 | 0.805402 | 0.244611 |
2 | 2 | 0.862707 | 0.862707 |
3 | 2 | 0.795719 | 0.862707 |
4 | 3 | 0.812910 | 0.812910 |
TibbleGrouped: g (n=3)
In [4]:
Copied!
df >> \
group_by(f.g) >> \
with_groups(None, mutate, x_mean = mean(f.x))
df >> \
group_by(f.g) >> \
with_groups(None, mutate, x_mean = mean(f.x))
Out[4]:
g | x | x_mean | |
---|---|---|---|
<int64> | <float64> | <float64> | |
0 | 1 | 0.244611 | 0.70427 |
1 | 1 | 0.805402 | 0.70427 |
2 | 2 | 0.862707 | 0.70427 |
3 | 2 | 0.795719 | 0.70427 |
4 | 3 | 0.812910 | 0.70427 |
In [5]:
Copied!
df >> \
group_by(f.g) >> \
with_groups(None, mutate, g=None)
df >> \
group_by(f.g) >> \
with_groups(None, mutate, g=None)
Out[5]:
x | |
---|---|
<float64> | |
0 | 0.244611 |
1 | 0.805402 |
2 | 0.862707 |
3 | 0.795719 |
4 | 0.812910 |