如何确定Pandas列是否包含特定值 [英] How to determine whether a Pandas Column contains a particular value
问题描述
我试图确定Pandas列中是否有一个具有特定值的条目.我试图用if x in df['id']
做到这一点.我以为这是行得通的,除了当我输入一个我知道不在列43 in df['id']
中的值时,它仍然返回True
.当我将一个子集添加到一个仅包含与缺少的ID df[df['id'] == 43]
匹配的条目的数据框时,显然其中没有任何条目.如何确定Pandas数据框中的列是否包含特定值,为什么我的当前方法不起作用? (仅供参考,当我在对此类似问题的 answer 中使用实现时,我遇到了同样的问题.
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).
推荐答案
系列的
in
检查值是否在索引中:
in
of a Series checks whether the value is in the index:
In [11]: s = pd.Series(list('abc'))
In [12]: s
Out[12]:
0 a
1 b
2 c
dtype: object
In [13]: 1 in s
Out[13]: True
In [14]: 'a' in s
Out[14]: False
一种选择是查看其是否为唯一值:
One option is to see if it's in unique values:
In [21]: s.unique()
Out[21]: array(['a', 'b', 'c'], dtype=object)
In [22]: 'a' in s.unique()
Out[22]: True
或python设置:
In [23]: set(s)
Out[23]: {'a', 'b', 'c'}
In [24]: 'a' in set(s)
Out[24]: True
如@DSM所指出的那样,直接在这些值上使用可能会更有效(特别是如果您仅对一个值执行此操作):
As pointed out by @DSM, it may be more efficient (especially if you're just doing this for one value) to just use in directly on the values:
In [31]: s.values
Out[31]: array(['a', 'b', 'c'], dtype=object)
In [32]: 'a' in s.values
Out[32]: True
这篇关于如何确定Pandas列是否包含特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!