我有一个流光多选择为不同的客户,其中我只想得到的产品,是共同的选定客户。
我的熊猫数据:
customer product version
A iphone 11
A ipad 7
B iphone 11
B ipad 7
B iMac 2012
我想得到一个只存在于bot客户A和B的产品清单,用于另一个选择。
Expected Output:
['iphone', 'ipad']
有什么想法吗?
发布于 2022-06-27 15:08:26
首先,我将获得与A相关的产品列表,以及与B相关的产品列表:
product_A = df.loc[df['customer'] == 'A', 'product'].to_list()
product_B = df.loc[df['customer'] == 'B', 'product'].to_list()
给予:
product_A
['iphone', 'ipad']
product_B
['iphone', 'ipad', 'iMac']
然后获取所有可能的产品的列表(删除重复的产品):
products = df['product'].drop_duplicates().to_list()
['iphone', 'ipad', 'iMac']
然后,您可以使用列表理解来检查产品中的每一项是否都在product_A
和product_B
中。
[i for i in products if (i in product_A) and (i in product_B)]
['iphone', 'ipad']
发布于 2022-06-27 20:03:09
以下是解决这一问题的一种方法。
代码
import streamlit as st
import pandas as pd
data = {
'customer': ['A', 'A', 'B', 'B', 'B', 'C'],
'product': ['iphone', 'ipad', 'iphone', 'ipad', 'iMac', 'ipad'],
'version': ['11', '7', '11', '7', '2012', '7']
}
df = pd.DataFrame(data)
st.write('### Initial df')
st.write(df)
customer_sel = st.multiselect('select customer', df.customer.unique())
if customer_sel:
# Build a dataframe based on the selected customers.
dflist = []
for c in customer_sel:
dfp = df.loc[(df.customer == c)]
dflist.append(dfp)
if dflist:
st.write('### products from selected customers')
dfsel = pd.concat(dflist)
st.write(dfsel)
# Create a dict where product is the key. A product with more than 1
# value will be our common product.
keys = dfsel["product"].unique()
common = {key: 0 for key in keys}
# print(common)
# Group the customer and product.
gb = dfsel.groupby(["customer", "product"])
# The name is a tuple of unique (customer, product) from groupby gb.
for name, _ in gb:
p = name[1] # get the product only
# Count the product from groupby.
common[p] += 1 if common.get(p, None) is not None else 0
# A product is common when it is selected at least once by each customer.
num_customer_sel = len(customer_sel)
common_product = [k for k, v in common.items() if v >= num_customer_sel]
if common_product:
st.write('### Common products from selected customers')
st.write(str(common_product))
产出1
产出2
https://stackoverflow.com/questions/72773240
复制相似问题