小编Nie*_*ers的帖子

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

我正在使用在数据帧中转换为字符串(年)的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 …
Run Code Online (Sandbox Code Playgroud)

python datetime series strftime pandas

4
推荐指数
1
解决办法
294
查看次数

标签 统计

datetime ×1

pandas ×1

python ×1

series ×1

strftime ×1