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

其他回答

我有一个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)

这工作。希望这能有所帮助!

Use

df[df['id']==x].index.tolist()

如果x存在于id中,那么它将返回它所在位置的索引列表,否则它将给出一个空列表。

使用query()查找符合条件的行,并获得形状为[0]的行数。如果存在至少一个条目,则此语句为True:

df.query('id == 123').shape[0] > 0

或者用级数。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做了一个关于一个系列的列表,而另一个我只是从一个常规系列中获得一个布尔系列,然后检查是否有任何真布尔系列。

Series的in检查该值是否在索引中:

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

一种选择是查看它是否为唯一值:

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所指出的,直接在值上使用in可能更有效(特别是如果你只对一个值执行此操作):

In [31]: s.values
Out[31]: array(['a', 'b', 'c'], dtype=object)

In [32]: 'a' in s.values
Out[32]: True