Confusing behavior when checking for values in a pandas series which contains both strings and integers

Viewed 46

I have a pandas series of dtype: object that contains both numbers and characters. When I wanted to check if a certain value exists in that series I got confused by the way how the existence of a certain value is checked.

For the example below, I would intuitively expect, that 'a' is in the series and also '1'. Furthermore, I wouldn't expect that the (integer) value 1 exists in the series, because AFAIK the dtype: object in pandas can be (roughly?) compared with python's string type.

Does anyone has an an explanation for this behavior?

s = pd.Series(['a',1,2])

if 'a' in  s: 
    print('a is in s')
else:
    print('a is not in s')
if '1' in s:
    print('string 1 is in s')
else: 
    print('string 1 is not in s')
if 1 in s:
    print('integer 1 is in s')
else:
    print('integer 1 is not in s')

Output:

a is not in s
string 1 is not in s
integer 1 is in s
1 Answers

When you are querying 1 in s you are actually asking if it is in s.index. Note that 0 in s will also be True.

If you define s in the following way - s = pd.Series(['a',1,2], index=['a', 'b', 'c'])

Then -

1 in s #False

'a' in s #True

And it has nothing to do with the values themselves.

Related