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).
当前回答
使用query()查找符合条件的行,并获得形状为[0]的行数。如果存在至少一个条目,则此语句为True:
df.query('id == 123').shape[0] > 0
其他回答
found = df[df['Column'].str.contains('Text_to_search')]
print(found.count())
find .count()将包含匹配数
如果它是0,那么意味着字符串没有在列中找到。
你可以试着检查一个名为“id”的列中的特定值“x”
if x in df['id'].values
你也可以使用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
假设你的数据框架是这样的:
现在你要检查文件名“80900026941984”是否存在于数据帧中。
你可以简单地写:
if sum(df["filename"].astype("str").str.contains("80900026941984")) > 0:
print("found")
使用query()查找符合条件的行,并获得形状为[0]的行数。如果存在至少一个条目,则此语句为True:
df.query('id == 123').shape[0] > 0
推荐文章
- 如何从生成器构建numpy数组?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和
- 如何避免在为Python项目构建Docker映像时重新安装包?
- 如何激活蟒蛇环境
- 省略[…]意思是在一个列表里?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201