I use the following dataframe
df = pd.DataFrame({'class': 'a a aa aa b b '.split(),
'item': [5,5,7,7,7,6],
'last_PO_code': ['103','103','103','104','103','104'],
'qty': [5,4,7,6,7,6]
})
I need to apply rules to this dataframe for each class in each item.
- true if all last_PO_code are equal to 103
- true if last_PO_code contains 103 and 104 and sum of qty 103 > sum qty of 104
- true if there is a last_PO_code equal to 103 and 104 and 105 and 106 and the sum of the qty of 104 == 103 and 105 == 106
I have written lambda functions that I can't use with transform
regle1 = lambda x: True if x['last_PO_code'].all() == "103" else False
regle2 = lambda x: x.loc[x['last_PO_code'].eq('103'), 'qty'].sum() \
> x.loc[x['last_PO_code'].eq('104'), 'qty'].sum()
regle3 = lambda x: x.loc[x['last_PO_code'].eq('105'), 'qty'].sum() \
== x.loc[x['last_PO_code'].eq('106'), 'qty'].sum()
df['regle1'] = df['class'].map(df.groupby(['class','item']).apply(regle1))
df['regle2'] = df['class'].map(df.groupby(['class','item']).apply(regle2))
df['regle3'] = df['class'].map(df.groupby(['class','item']).apply(regle3))
mask1 = df['regle2'] == True
mask2 = df['regle3'] == True
mask = mask1 & mask2
df['regle3'] = np.where(mask,True,False)
which I would like to transform into a function like the following to use transform and not apply
I succeeded with rule 1 but I can't manage with the other rules
def regle1(x):
return (x == '103').all()
df['regle1'] = df.groupby(['class', 'item']).last_PO_code.transform(regle1)