I have a dataframe e.g.:
my_label value
0 A 1
1 A 85
2 B 65
3 B 41
4 B 21
5 C 3
I want to group by my_label and to pad groups to a certain length modulo and filling by last value. For example if I want to have multiple of 4, it would give :
my_label value
0 A 1
1 A 85
2 A 85
3 A 85
4 B 65
5 B 41
6 B 21
7 B 21
8 C 3
9 C 3
10 C 3
11 C 3
I managed to get a solution that should be working, but for some reason the reindex isn't done at the end of the groups.
def _pad(group, seq_len):
pad_number = seq_len - (len(group) % seq_len)
if pad_number != seq_len:
group = group.reindex(range(len(group)+pad_number)).ffill()
return group
df = (df.groupby('my_label')
.apply(_pad, (4))
.reset_index(drop = True))
Here is the code to the above DF for testing :
import pandas as pd
df = pd.DataFrame({"my_label":["A","A","B","B","B","C"], "value":[1,85,65,41,21,3]})