【问题标题】:Check whether an item appears previously in a list of items using Python Pandas使用 Python Pandas 检查项目是否以前出现在项目列表中
【发布时间】:2018-11-17 12:02:00
【问题描述】:

我有下表,其中有 ID,对于每个 ID,我有篮子 1、篮子 2,最后是篮子中的产品。

我想在 sorted 表(按 AZ、Basket 1 ASC 和 Basket 2 ASC 的 ID 排序)上查找 每个 ID 的每个产品是否以前出现过(对于相同的 ID)并将 Y 或 N 放入新列(E 列)。

第一个 ID 的示例如下:

111AAA222 = [Product1, Product2, Product3, Product1, Product2, Product3, Product1, Product4]

111AAA222 = [N, N, N, Y, Y, Y, Y, N]

该示例显示列表中第 3 位到第 6 位的产品之前出现在同一列表中。

我很难使用 python pandas 创建具有 Y 和 N 值的新列(列 E:已存在)。

【问题讨论】:

  • 请查看How to Ask,不幸的是,SO 不是免费的代码编写服务。此外,代码应该以文本形式发布,而不是图片。

标签: python list pandas


【解决方案1】:

创建一个df_new,在其中对数据进行排序,然后将重复项放在“ID”和“产品”两列上。然后创建用 N 填充的 Existed 列,因为 df_new 中的行不是重复的

df_new = df.sort_values(['ID','Basket 1','Basket 2'],0)[['ID','Product']].drop_duplicates()
df_new['Existed'] = 'N'

现在join 这一列df_new['Existed'] 使用您的df 并用'Y' 填充缺失值

df = df.join(df_new['Existed']).fillna('Y')

如果您想要产品列表并已存在,请打印此列表

df.groupby('ID')['Product','Existed'].agg(lambda x: list(x))

【讨论】:

    猜你喜欢
    • 2017-12-21
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2011-09-02
    • 1970-01-01
    • 2018-07-07
    • 2021-07-28
    相关资源
    最近更新 更多