首页 > 解决方案 > 检查值是否在 DataFrame 系列中(“系列的真值不明确”错误)

问题描述

我正在尝试检查 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)

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

标签: pythonpandasdataframe

解决方案


我们可以apply用来检查 in 存在的少数情况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

推荐阅读