I am trying to determine whether there is an entry in a Pandas column that has a particular value. I tried to do this with if x in df['id']. I thought this was working, except when I fed it a value that I knew was not in the column 43 in df['id'] it still returned True. When I subset to a data frame only containing entries matching the missing id df[df['id'] == 43] there are, obviously, no entries in it. How to I determine if a column in a Pandas data frame contains a particular value and why doesn't my current method work? (FYI, I have the same problem when I use the implementation in this answer to a similar question).
当前回答
found = df[df['Column'].str.contains('Text_to_search')]
print(found.count())
find .count()将包含匹配数
如果它是0,那么意味着字符串没有在列中找到。
其他回答
简单的条件:
if any(str(elem) in ['a','b'] for elem in df['column'].tolist()):
或者用级数。tolist或Series.any:
>>> s = pd.Series(list('abc'))
>>> s
0 a
1 b
2 c
dtype: object
>>> 'a' in s.tolist()
True
>>> (s=='a').any()
True
系列。tolist做了一个关于一个系列的列表,而另一个我只是从一个常规系列中获得一个布尔系列,然后检查是否有任何真布尔系列。
我有一个CSV文件要读取:
df = pd.read_csv('50_states.csv')
在尝试之后:
if value in df.column:
print(True)
即使值在列中,它也不会输出true;
我试着:
for values in df.column:
if value == values:
print(True)
#Or do something
else:
print(False)
这工作。希望这能有所帮助!
你也可以使用pandas.Series.isin,尽管它比s.values中的'a'长一点:
In [2]: s = pd.Series(list('abc'))
In [3]: s
Out[3]:
0 a
1 b
2 c
dtype: object
In [3]: s.isin(['a'])
Out[3]:
0 True
1 False
2 False
dtype: bool
In [4]: s[s.isin(['a'])].empty
Out[4]: False
In [5]: s[s.isin(['z'])].empty
Out[5]: True
但是,如果您需要为一个DataFrame同时匹配多个值,这种方法可以更加灵活。
>>> df = DataFrame({'A': [1, 2, 3], 'B': [1, 4, 7]})
>>> df.isin({'A': [1, 3], 'B': [4, 7, 12]})
A B
0 True False # Note that B didn't match 1 here.
1 False True
2 True True
使用query()查找符合条件的行,并获得形状为[0]的行数。如果存在至少一个条目,则此语句为True:
df.query('id == 123').shape[0] > 0
推荐文章
- 有哪些好的Python ORM解决方案?
- 如何在f字符串中转义括号?
- Python void返回类型注释
- 如何为python模块的argparse部分编写测试?
- 在python中是否有用于均方根误差(RMSE)的库函数?
- 如何从matplotlib (pyplot。Figure vs matplotlib。figure) (frameon=False matplotlib中有问题)
- django test app error -在创建测试数据库时出现错误:创建数据库的权限被拒绝
- 识别使用pip安装的python包的依赖关系
- 从字符串变量导入模块
- 如何删除Python中的前导空白?
- python中的assertEquals和assertEqual
- 如何保持Python打印不添加换行符或空格?
- 为什么Python的无穷散列中有π的数字?
- Python 3.7数据类中的类继承
- 如何在PyTorch中初始化权重?