Issue
I have a streamlit multi-select for different customers, of which I would like only get products which are common to the selected customers.
My pandas dataframe:
customer product version
A iphone 11
A ipad 7
B iphone 11
B ipad 7
B iMac 2012
I would like to get a list of only the products which exists for bot Customer A and B, to be used in another select.
Expected Output:
['iphone', 'ipad']
Any ideas?
Solution
I would first get a list of the products associated to A, and the ones associated to B:
product_A = df.loc[df['customer'] == 'A', 'product'].to_list()
product_B = df.loc[df['customer'] == 'B', 'product'].to_list()
Gives:
product_A
['iphone', 'ipad']
product_B
['iphone', 'ipad', 'iMac']
Then get a list of all the possible products (with duplicates removed):
products = df['product'].drop_duplicates().to_list()
['iphone', 'ipad', 'iMac']
You can then use list comprehension to go through each item in products to check if it is both in product_A
and product_B
:
[i for i in products if (i in product_A) and (i in product_B)]
['iphone', 'ipad']
Answered By - Emi OB
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.