【发布时间】:2019-01-28 11:22:56
【问题描述】:
我正在处理在数据框中转换为字符串(年)的日期时间值。我想使用 in 运算符检查我的 dataframe.year_as_string 列中是否存在给定的年份。但是,我的表达式意外地计算为 False(请参阅第二个打印语句)。为什么会这样?
注意:我可能可以用更简单的方式解决我的问题(如在第三条打印语句中),但我真的很好奇为什么第二条语句的计算结果为 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)
【问题讨论】:
-
看起来
df['year_as_string'])不像您想象的那样是一个列表。 (我的第一个行动方案是print(type(df['year_as_string']))。)
标签: python pandas datetime series strftime