Python in operator not working as expected when comparing string and strftime values [duplicate] Python in operator not working as expected when comparing string and strftime values [duplicate] pandas pandas

Python in operator not working as expected when comparing string and strftime values [duplicate]


The in operator with a Pandas series will check the index, much like using in with a dictionary will check keys only. Instead, you can use in with a series' NumPy array representation:

'2013' in df['year_as_string'].values

A more Pandorable approach would be to construct a Boolean series and then use pd.Series.any:

(df['year_as_string'] == '2013').any()

Equivalently:

df['year_as_string'].eq('2013').any()

Even better, avoid converting to strings unless absolutely necessary:

df['year_as_int'] = df['year'].dt.yeardf['year_as_int'].eq(2013).any()


In your second statement it checks the index numbers and not the values of the column. If you want to check the values you can use:

print('2013' in df.to_string(index = False, columns=['year_as_string']))))


in on a pandas.Series checks whether something is in the index, just like a dict. documentation