【问题标题】:Check if the values in the df matches any of the values of the dict检查 df 中的值是否与 dict 的任何值匹配
【发布时间】:2021-07-31 19:26:07
【问题描述】:

df-

orderid supplierid name other columns
101 1 x
102 1 z
103 2 x

字典-

{1: {'name': ['x', 'y']},
 2: {'name': ['z']}}

我的最终目标是检查为特定 id 指定的名称是否与 dict 中的任何值匹配,并用 yes 或 no 填充新列“exist_or_not”。

预期结果-

orderid supplierid name exist_or_not
101 1 x yes
102 1 z no
103 2 x no

我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x pandas dataframe dictionary


    【解决方案1】:

    首先使用嵌套列表解析创建 DataFrame,然后在 DataFrame.merge 中使用带有 indicator 参数的左连接,最后在 numpy.where 中创建 yes, no

    d = {1: {'name': ['x', 'y']}, 2: {'name': ['z']}}
    
    df1 = pd.DataFrame([(k, x) 
                       for k, v in d.items() 
                       for k1, v1 in v.items() 
                       for x in v1], columns=['supplierid','name'])
    print (df1)
       supplierid name
    0           1    x
    1           1    y
    2           2    z
    

    df = df.merge(df1, on=['supplierid','name'], how='left', indicator='exist_or_not')
    
    df['exist_or_not'] = np.where(df['exist_or_not'].eq('both'), 'yes', 'no')
    print (df)
       orderid  supplierid name exist_or_not
    0      101           1    x          yes
    1      102           1    z           no
    2      103           2    x           no
    

    【讨论】:

      【解决方案2】:

      列表理解

      df["exists_or_not"] = ["yes"
                             if the_name in d[sup_id]["name"]
                             else "no"
                             for the_name, sup_id in zip(df.name, df.supplierid)]
      

      其中d 是您的字典{1: {'name': ['x', 'y']}, 2: {'name': ['z']}}

      得到

         orderid  supplierid name exists_or_not
      0      101           1    x           yes
      1      102           1    z            no
      2      103           2    x            no
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-31
        • 2019-08-16
        • 1970-01-01
        • 2018-06-27
        • 2019-08-25
        相关资源
        最近更新 更多