Michael - 1 year ago 73

Python Question

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']`

`43 in df['id']`

`True`

`df[df['id'] == 43]`

Answer Source

`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
```

or a python set:

```
In [23]: set(s)
Out[23]: {'a', 'b', 'c'}
In [24]: 'a' in set(s)
Out[24]: True
```

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
```