2
votes

I am trying to split a dataframe into multiple sub dataframes. So far I was using:

a = pd.Series(1, 2, 3, 4, 5, 6, 7, 8 ,9, 10)
df = pd.DataFrame(data=a)
def split(df, chunkSize = 3):
    return np.array_split(df, chunkSize)

The problem is, that this returns me 3 dataframes (123; 456; 789), but what I am trying to get, is every possible chunk of 3 numbers that is contained in the df. So in this case: (123, 234, 345, 456, 567, 678, 8910). I am aware of the other questions about splitting dataframes, but I still couldnt find this specific problem. Is there a simple way to solve this?

1

1 Answers

1
votes

Here is one way:

import itertools
def split_chunk(series,chunk):
    return [[*g][0] for k,g in (itertools.groupby([*itertools.combinations(series,chunk)]
                                         ,key=operator.itemgetter(0)))]

split_chunk(df[0],3)

Output:

[(1, 2, 3),
 (2, 3, 4),
 (3, 4, 5),
 (4, 5, 6),
 (5, 6, 7),
 (6, 7, 8),
 (7, 8, 9),
 (8, 9, 10)]