首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于多选择选项的流光多选择获取公共值

基于多选择选项的流光多选择获取公共值
EN

Stack Overflow用户
提问于 2022-06-27 13:50:25
回答 2查看 35关注 0票数 0

我有一个流光多选择为不同的客户,其中我只想得到的产品,是共同的选定客户。

我的熊猫数据:

代码语言:javascript
运行
复制
customer  product version
A         iphone  11
A         ipad    7
B         iphone  11
B         ipad    7
B         iMac    2012

我想得到一个只存在于bot客户A和B的产品清单,用于另一个选择。

代码语言:javascript
运行
复制
Expected Output:
['iphone', 'ipad']

有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-06-27 15:08:26

首先,我将获得与A相关的产品列表,以及与B相关的产品列表:

代码语言:javascript
运行
复制
product_A = df.loc[df['customer'] == 'A', 'product'].to_list()
product_B = df.loc[df['customer'] == 'B', 'product'].to_list()

给予:

代码语言:javascript
运行
复制
product_A
['iphone', 'ipad']
product_B
['iphone', 'ipad', 'iMac']

然后获取所有可能的产品的列表(删除重复的产品):

代码语言:javascript
运行
复制
products = df['product'].drop_duplicates().to_list()
['iphone', 'ipad', 'iMac']

然后,您可以使用列表理解来检查产品中的每一项是否都在product_Aproduct_B中。

代码语言:javascript
运行
复制
[i for i in products if (i in product_A) and (i in product_B)]
['iphone', 'ipad']
票数 0
EN

Stack Overflow用户

发布于 2022-06-27 20:03:09

以下是解决这一问题的一种方法。

代码

代码语言:javascript
运行
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72773240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档