Let's say I have the following product descriptions in a Pandas DataFrame. I would like to keep all product descriptions of products that satisfy the following condition:
For every
idinproduct_descriptions, check if it contains alldescriptionsfrom at least 1 scenario inscenario_descriptions. If so, check if the descriptions of all these scenarios havestatus4, 5 or 6.
Input
scenario_descriptions = [
['world1', 'world2', 'world3'], #scenario1
['world4', 'world2'], #scenario2
['world5'], #scenario3
['world6', 'world7'], #scenario4
['world6', 'world2'] #scenario5
]
product_descriptions =
id | description | status
-------------------------
1 | world1 | 1
1 | world2 | 4
1 | world3 | 1
1 | world4 | 4
1 | world5 | 4
1 | world6 | 4
1 | world7 | 1
1 | world8 | 4
1 | world9 | 4
1 | world10 | 4
1 | world11 | 4
1 | world12 | 4
1 | world13 | 4
1 | world14 | 4
1 | world15 | 1
2 | world1 | 1
2 | world2 | 1
2 | world3 | 5
2 | world15 | 6
2 | world8 | 6
2 | world4 | 5
2 | world7 | 5
Product with id == 1 is not excluded because:
- It has
world2 andworld4` (scenario2) and their statuses are 4 - It has
world5(scenario3) with status 4 - It has
world6andworld2(scenario5) with status 4
Product with id == 2 is excluded because:
world1(scenario1) doesn't have status 4, 5 or 6world2(scenario2) doesn't have status 4, 5 or 6- It doesn't have
world5(scenario3) - It doesn't have
world6(scenario4) - It doesn't have
world6(scenario5) and status ofworld2is not 4, 5 or 6
Output
filtered_product_descriptions =
id | description | status
-------------------------
1 | world1 | 1
1 | world2 | 4
1 | world3 | 1
1 | world4 | 4
1 | world5 | 4
1 | world6 | 4
1 | world7 | 1
1 | world8 | 4
1 | world9 | 4
1 | world10 | 4
1 | world11 | 4
1 | world12 | 4
1 | world13 | 4
1 | world14 | 4
1 | world15 | 1
Any idea how to solve this? I have been trying for days, but no success :( The code below is the closest I could get. This solves the first section of my problem. I don't know how to combine this with the second condition:
If so, check if the descriptions of all these scenarios have status 4, 5 or 6.
filtered_product_descriptions = (product_descriptions.groupby('id').filter(lambda x: (pd.Series([(pd.Series(y).isin(x['description']).all()) for y in scenario_descriptions])).any()))