运算符中的Python在比较字符串和strftime值时未按预期工作

Nie*_*ers 4 python datetime series strftime pandas

我正在使用在数据帧中转换为字符串(年)的datetime值.我想使用in运算符检查我的dataframe.year_as_string列中是否存在给定年份.但是,我的表达式意外地计算为False(请参阅第二个print语句).为什么会这样?

注意:我可以用更简单的方式解决我的问题(如在第3个print语句中),但我真的很好奇为什么第二个语句的计算结果为False.

import pandas as pd

ind = pd.to_datetime(['2013-12-31', '2014-12-31'])

df = pd.DataFrame([1, 2], index=ind)
df = df.reset_index()
df.columns = ['year', 'value']
df['year_as_string'] = df.year.dt.strftime('%Y')

# 1. the string '2013' is equal to the first element of the list
print('2013' == df['year_as_string'][0])

# 2. but that same string is not 'in' the list?! Why does this evaluate to False?
print('2013' in df['year_as_string'])

# 3. I further saw that strftiming the DatetimeIndex itself does evaluate as I would expect
year = ind.strftime('%Y')
print('2013' in year)
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 6

in具有Pandas系列的运算符将检查索引,就像使用in字典仅检查键一样.相反,您可以使用in一系列'NumPy数组表示:

'2013' in df['year_as_string'].values
Run Code Online (Sandbox Code Playgroud)

更可靠的方法是构造一个布尔系列,然后使用pd.Series.any:

(df['year_as_string'] == '2013').any()
Run Code Online (Sandbox Code Playgroud)

等价的:

df['year_as_string'].eq('2013').any()
Run Code Online (Sandbox Code Playgroud)

更好的是,除非绝对必要,否则不要转换为字符串

df['year_as_int'] = df['year'].dt.year
df['year_as_int'].eq(2013).any()
Run Code Online (Sandbox Code Playgroud)