I was trying to divide the month into two weeks. Basically for each month i am trying to create week numbers like 1,2,3,4 and repeat them.
How to create the required column like below:
JavaScript
x
31
31
1
import numpy as np
2
import pandas as pd
3
4
5
df = pd.DataFrame({'Year_Month':['2020-jan']*6+['2020-feb']+['2021-jan']*2+['2021-jan']+['2021-mar']*5})
6
df['B'] = [1]*6+[5]+[1]*2+[1]+[10]*5
7
df['groubyA_repeatB'] = [1,2,3,4,1,2,
8
5,
9
1,2,3,
10
10,11,12,13,10] # groupby column A and repeat [i,i+1,i+2,i+3]
11
12
# e.g. for group A: we have 8 'a' and value of a is 1, so we need to repeat [1,2,3,4] until we get 8 elements.
13
df
14
15
Year_Month B groubyA_repeatB # how to create this column
16
0 2020-jan 1 1
17
1 2020-jan 1 2
18
2 2020-jan 1 3
19
3 2020-jan 1 4
20
4 2020-jan 1 1
21
5 2020-jan 1 2
22
6 2020-feb 5 5
23
7 2021-jan 1 1
24
8 2021-jan 1 2
25
9 2021-jan 1 3
26
10 2021-mar 10 10
27
11 2021-mar 10 11
28
12 2021-mar 10 12
29
13 2021-mar 10 13
30
14 2021-mar 10 10
31
Advertisement
Answer
You can utilize cycle
to create cycle for list and slice
to get specific count
JavaScript
1
6
1
from itertools import cycle, islice
2
3
out = (df
4
.groupby(['Year_Month', 'B'])
5
.apply(lambda g: g.assign(groubyA_repeatB_=list(islice(cycle(range(g.iloc[0]['B'], g.iloc[0]['B']+4)), len(g))))))
6
JavaScript
1
19
19
1
print(out)
2
3
Year_Month B groubyA_repeatB groubyA_repeatB_
4
0 2020-jan 1 1 1
5
1 2020-jan 1 2 2
6
2 2020-jan 1 3 3
7
3 2020-jan 1 4 4
8
4 2020-jan 1 1 1
9
5 2020-jan 1 2 2
10
6 2020-feb 5 5 5
11
7 2021-jan 1 1 1
12
8 2021-jan 1 2 2
13
9 2021-jan 1 3 3
14
10 2021-mar 10 10 10
15
11 2021-mar 10 11 11
16
12 2021-mar 10 12 12
17
13 2021-mar 10 13 13
18
14 2021-mar 10 10 10
19