I have a dataframe with 2 columns:
- employee_num (from 0 to 4999)
- risk, which only has 3 values - high, med and low. They are randomly distributed between the dataframe.
I need to add a third column, called checker, which has 5 values - 1,2,4,6,8. Those checkers need to be evenly distributed between the risk values. There can be a difference of 1, since the risk levels not necessarily divided by 5.
For example, if my df is 5000 rows, and the risk is distributed: high 2537 low 1470 med 993
Then high would by distributed: 1:507, 2:507, 4:507, 6:508, 8:508 >> 2537 overall.
I tried the following:
workers = pd.DataFrame()
workers['employee_num'] = np.arange(5000)
risk = ['high', 'med', 'low']
workers['risk'] = np.random.choice(risk, size=len(workers), p=[0.5,0.2,0.3])
workers.groupby('risk').size()
worker = workers.copy()
df1 = pd.DataFrame()
df2 = pd.DataFrame()
df3 = pd.DataFrame()
df4 = pd.DataFrame()
df5 = pd.DataFrame()
And then:
def func(df1, df2, df3, df4, df5):
grp = [1,2,4,6,8]
for i, df in enumerate([df1, df2, df3, df4, df5]):
df = worker.groupby('risk').sample(frac=(len(worker)/len(grp))/len(worker), replace=False, random_state=0)
print(1, worker.shape)
print(2, df.shape)
worker.drop(df.index.values, axis=0, inplace=True)
print(3, worker.shape)
df['checker'] = grp[i]
yield df
But after i concat it back together, i'm left with just part of the data i started with:
df1, df2, df3, df4, df5 = func(df1, df2, df3, df4, df5)
worker = pd.concat([df1, df2, df3, df4, df5],axis=0)
I would be most grateful for a solution to this (been sitting on this for hours). Thank you!