【问题标题】:Check to see if value is in DataFrame series ("The truth value of a Series is ambiguous" error)检查值是否在 DataFrame 系列中(“系列的真值不明确”错误)
【发布时间】:2019-06-13 06:58:14
【问题描述】:

我正在尝试检查 DataFrame 列中的值是否包含在单独列中的系列中。我收到“ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”

我对此进行了研究,但不太明白为什么我会在此特定情况下收到此错误。

我尝试过使用这两个 .contains 函数。

DataFrame结构的简化版如下:

df

index     id       id_list           in_series (desired return column]
1         23       [1,2,34,56,75]    False
2         14       [1,5,14,23,45]    True
3         2        [1,2,4,25,37]     True
4         14       [2,4,34,26,77]    False
5         27       [1,6,19,27,50]    True

a = df['id']
b = df['id_list]
df['in_series'] = b.str.contains(a, regex=False)

有没有更好的方法来解决这个问题?

【问题讨论】:

  • JohanC 谢谢!正要改写我的问题,但这完美地回答了它。

标签: python pandas dataframe


【解决方案1】:

我们可以使用apply 来检查id 是否存在于id_list 中的少数情况之一:

df['in_series'] = df.apply(lambda x: str(x['id']) in ', '.join(str(y) for y in x['id_list']),axis=1)

   id             id_list  in_series
0  23  [1, 2, 34, 56, 75]      False
1  14  [1, 5, 14, 23, 45]       True
2   2   [1, 2, 4, 25, 37]       True
3  14  [2, 4, 34, 26, 77]      False
4  27  [1, 6, 19, 27, 50]       True

【讨论】:

    【解决方案2】:

    你仍然可以使用循环

    id_list=[[1,2,34,56,75],[1,5,14,23,45],[1,2,4,25,37],[2,4,34,26,77],[1,6,19,27,50]]
    id=[23,14,2,14,27]
    df=pd.DataFrame([id,id_list]).T
    df.columns=["id","id_list"]
    
    boo=list()
    for i in range(len(df)):
        boo.append(df.iloc[i,0] in df.iloc[i,1])
    
    df["in_series (desired return column]"]=boo
    

    在这种情况下,您无需更改数据类型

    【讨论】:

      【解决方案3】:

      一点列表理解魔法应该会起作用:

      df['in_series (desired return column'] = ([df.id[i].astype(str) in df.id_list[i] 
                                                for i in range(len(df))])
      
      
      
         print(df)
              index   id  id_list in_series (desired return column)
      0   1   23  [1,2,34,56,75]  False
      1   2   14  [1,5,14,23,45]  True
      2   3   2   [1,2,4,25,37]   True
      3   4   14  [2,4,34,26,77]  False
      4   5   27  [1,6,19,27,50]  True
      

      【讨论】:

        猜你喜欢
        • 2018-01-11
        • 1970-01-01
        • 2021-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多