python - 检查值是否在 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)
有没有更好的方法来解决这个问题?
解决方案
我们可以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
推荐阅读
- asp.net-core - Blazor Server / Asp.Net Core:在 IIS 上发布时,Http 请求不会将用户身份传递给 MVC 控制器
- visual-studio-code - 为什么我的 VS Code 终端不断被终止?
- django - Django中自定义格式的唯一ID生成器
- node.js - discord.js 获取用户集成
- bots - 如何让我的不和谐机器人阅读其他机器人嵌入消息
- html - 无法从 mat-chip 中删除悬停背景颜色
- styleframe - StyleFrame(或 styleframe?)导入问题
- c - 二进制数:+ 和 | 之间的奇怪差异
- scala - 在 Scala 集合的 .groupBy() 操作中维护顺序
- jquery - 基于项目计数的猫头鹰轮播项目选项