I failed in my attempt to group Dataframes by 'tag', expecting to turn their rolling 4 'sales' into a list, my code:
df = pd.DataFrame({
'sales': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
'tag': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C']})
df.groupby('tag')['sales'].rolling(4).apply(lambda x: x.tolist())
The error message is as follows: TypeError: must be real number, not list
I can suggest the following option: the data is aggregated into a list and a slice
[:4]is taken, that is, take the first four values, if there are less than4, then returnnp.nan.Output:
if you need a dataframe:
Output:
exclude empty rows:
Output: