首页 > 解决方案 > 检查 Pandas 列中是否存在元素(系列)

问题描述

这个问题已经以几种形式发布,但由于某种原因,没有一个解决方案适用于我的用例。我有一个查找编号,它是我创建的类的一部分。我想简单地查看该数字是否存在于我的数据框的列中。以下是我尝试过的解决方案:

 # Where body_part.LookupNumber is a unique int and body_part.SymptomTable['BodyPartIllnessTypeId'] is a column of ints. 
 if body_part.LookupNumber in body_part.SymptomTable['BodyPartIllnessTypeId'].tolist():
      do something 
 
 # Get this error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() 

 # Fair enough, so then I tried this: 
 if body_part.LookupNumber in body_part.SymptomTable['BodyPartIllnessTypeId'].values:
     do something
 # Get this error ValueError: Lengths must match to compare

奇怪的是,当我运行它时,它会打印出来。在这种情况下,我将 i 实例化为一个类对象:

if i.LookupNumber in i.SymptomTable['BodyPartIllnessTypeId'].values:
 print('worked')

谢谢你的时间。

标签: pythonpandasnumpy

解决方案


非常感谢@Yonlif。这是我的一个严重错误。的类型body_part.LookupNumber实际上不是 int。


推荐阅读