I have a sample df which I am trying to create chunks where a given column value is spread equally (almost) among the chunks.
For example, consider the DF:
df = pd.DataFrame([["apple",1],["mango",20],["mango",20],["mango",31],["apple",17],
["apple",17],["mango",17],["mango",17],["mango",17],["mango",17],["mango",17],["mango",17],["mango",17],
["apple",17],["mango",17],["mango",17],["apple",17]
])
df.columns = ["fruit", "count"]
df
if I want to create 2 chunks of this df where the value for fruit column =apple gets split equally among the 2 chunks.
my current version, first create separate Dfs for mango and apple and then create the splits and concat corresponding splits.
Code:
df_apple = df.loc[df["fruit"]=="apple"]
df_apple_splits = np.array_split(df_apple,2)
df_mango = df.loc[df["fruit"]=="mango"]
df_mango_splits = np.array_split(df_mango,2)
df_split1 = pd.concat([df_apple_splits[0],df_mango_splits[0]])
df_split2 = pd.concat([df_apple_splits[1],df_mango_splits[1]])
But is there a more elegant way to do this?