I want to split this DataFrame into a predefined number of chunks of approximately the same size:
import pandas as pd
df = pd.DataFrame({
"user": ["A", "A", "B", "C", "C", "C"],
"value": [0.3, 0.4, 0.5, 0.6, 0.7, 0.8]})
# user value
# 0 A 0.3
# 1 A 0.4
# 2 B 0.5
# 3 C 0.6
# 4 C 0.7
# 5 C 0.8
The DataFrame is large (millions of lines) so the code should be more or less efficient. The problem is that certain user should only be present in one of the chunks.
E.g. if the number of chunks is 3 then:
- first chunk should have lines [0, 1]
- second chunk should have line 2, no line 3 since line 3 is for user C
- third chunk should have lines [3, 4, 5]
# Chunk #1 (DataFrame):
# 0 A 0.3
# 1 A 0.4
# Chunk #2 (DataFrame):
# 2 B 0.5
# Chunk #3 (DataFrame):
# 3 C 0.6
# 4 C 0.7
# 5 C 0.8
This chunking in 3 pieces will be incorrect since user C will be present in 2 chunks:
# Chunk #1 (DataFrame):
# 0 A 0.3
# 1 A 0.4
# Chunk #2 (DataFrame):
# 2 B 0.5
# 3 C 0.6
# Chunk #3 (DataFrame):
# 4 C 0.7
# 5 C 0.8
I think that some solution when we do groupby by user first and then split this DataFrameGroupBy object in chunks should suffice.