I have a large df of the following structure:
Grade Price Group
A 2 apple
A 10 apple
A 9 apple
A 10 apple
B 8 apple
B 7 apple
B 6 apple
B 10 apple
A 12 berry
A 11 berry
A 11 berry
A 12 berry
A 10 berry
B 9 berry
B 9 berry
B 10 berry
B 11 berry
I need to filter the df based on the below conditions for each Group. If it is an apple then the Grades should be within the below limit or else exclude those which violate for this Group. It has to check for each unique Group variable and check the price is in range of the corresponding grades.
apple
A 9-10
B 7-8
berry
A 11-12
B 9-10
The output df should then be having those only which meet the criteria.
Grade Price Group
A 10 apple
A 9 apple
A 10 apple
B 8 apple
B 7 apple
A 12 berry
A 11 berry
A 11 berry
A 12 berry
B 9 berry
B 9 berry
B 10 berry
I currently filter the dataframe that meet each condition and concatenate the resulting dataframes.
a = df[(df['Group'] == 'apple') & (df['Grade'] == 'A') & (df['Price'].between(9, 10))]
b = df[(df['Group'] == 'apple') & (df['Grade'] == 'B') & (df['Price'].between(7, 8))]
res = pd.concat([a,b])
and this is not optimal to write to multiple data frames for each condition.
Any efficient solution that excludes those that do not meet the criteria would be helpful.