Skip to content

Commit 85f8ade

Browse files
code sample for pandas-dev#36727
1 parent 6e2d063 commit 85f8ade

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

bisect/36727.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import numpy as np
2+
import pandas as pd
3+
4+
df = pd.DataFrame(
5+
[
6+
["A", "group_1", pd.Timestamp(2019, 1, 1, 9)],
7+
["B", "group_1", pd.Timestamp(2019, 1, 2, 9)],
8+
["C", "group_2", pd.Timestamp(2019, 1, 3, 9)],
9+
["D", "group_1", pd.Timestamp(2019, 1, 6, 9)],
10+
["E", "group_1", pd.Timestamp(2019, 1, 7, 9)],
11+
["F", "group_1", pd.Timestamp(2019, 1, 10, 9)],
12+
["G", "group_2", pd.Timestamp(2019, 1, 20, 9)],
13+
["H", "group_1", pd.Timestamp(2019, 4, 8, 9)],
14+
],
15+
columns=["index", "group", "eventTime"],
16+
).set_index("index")
17+
18+
groups = df.groupby("group")
19+
df["count_to_date"] = groups.cumcount()
20+
rolling_groups = groups.rolling("10d", on="eventTime")
21+
group_size = rolling_groups.apply(lambda df: df.shape[0])
22+
print(group_size)
23+
24+
index = pd.MultiIndex.from_tuples(
25+
[
26+
("group_1", "A"),
27+
("group_1", "B"),
28+
("group_1", "D"),
29+
("group_1", "E"),
30+
("group_1", "F"),
31+
("group_1", "H"),
32+
("group_2", "C"),
33+
("group_2", "G"),
34+
],
35+
names=["group", "index"],
36+
)
37+
38+
columns = pd.Index(["eventTime", "count_to_date"], dtype="object")
39+
40+
values = np.array(
41+
[
42+
[pd.Timestamp("2019-01-01 09:00:00"), 1.0],
43+
[pd.Timestamp("2019-01-02 09:00:00"), 2.0],
44+
[pd.Timestamp("2019-01-06 09:00:00"), 3.0],
45+
[pd.Timestamp("2019-01-07 09:00:00"), 4.0],
46+
[pd.Timestamp("2019-01-10 09:00:00"), 5.0],
47+
[pd.Timestamp("2019-04-08 09:00:00"), 1.0],
48+
[pd.Timestamp("2019-01-03 09:00:00"), 1.0],
49+
[pd.Timestamp("2019-01-20 09:00:00"), 1.0],
50+
],
51+
dtype=object,
52+
)
53+
54+
expected = pd.DataFrame(values, index=index, columns=columns)
55+
expected.count_to_date = expected.count_to_date.astype("float")
56+
57+
import pandas.testing as tm
58+
59+
tm.assert_frame_equal(group_size, expected)

0 commit comments

Comments
 (0)