I have a dataframe which I have grouped based on a column, I have to then merge these "grouped dataframes" to newer dataframes but under the condition that the newer dataframe must not have more than x rows (3 in this case), if it exceeds the count, I create a new df (else part in my code). I think I have a code that does this, but this is slow on my actual dataset, 300000 rows in dataframe.
Code
import pandas as pd
a = [1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3, 1, 1, 2, 3, 2, 2, 3]
df = pd.DataFrame({"a": a})
dfs = [pd.DataFrame()]
group = (df['a'] != df['a'].shift()).cumsum()
for i, j in df.groupby(group):
curRow = j.shape[0]
prevRow = dfs[-1].shape[0]
# is the new size greater than 3
if curRow + prevRow <= 3:
# less than 3 so add to the preivous df
dfs[-1] = dfs[-1].append(j)
else:
# greater than 3 so add this as a new df
dfs.append(j)
Expected Output
"dfs" will have 25 dataframes but faster than current code
Current Output
"dfs" will have 25 dataframes
For those asking the logic of group by
It is basically a itertools.groupby when you give a sequence that is not sorted,