我正在将日期时间值转换为数据帧中的字符串(年)。我想使用in
运算符检查我的dataframe.year_as_string列中是否存在给定的年份。但是,我的表达式意外地得出False(请参阅第二个打印语句)。为什么会这样?
NB:我可能可以以更简单的方式解决问题(如第3条打印语句中所示),但我很好奇为什么第二条语句的计算结果为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)
答案 0 :(得分:6)
带有熊猫系列的in
运算符将检查索引,就像将in
与字典一起使用将仅检查键一样。相反,您可以将in
与系列的NumPy数组表示形式配合使用:
'2013' in df['year_as_string'].values
一种更可恶的方法是构造一个布尔序列,然后使用pd.Series.any
:
(df['year_as_string'] == '2013').any()
等效地:
df['year_as_string'].eq('2013').any()
更好的是,除非绝对必要,否则避免转换为字符串:
df['year_as_int'] = df['year'].dt.year
df['year_as_int'].eq(2013).any()
答案 1 :(得分:2)
在第二条语句中,它检查索引号而不是列的值。如果要检查值,可以使用:
print('2013' in df.to_string(index = False, columns=['year_as_string']))))
答案 2 :(得分:1)
in
上的 pandas.Series
检查索引中是否包含某些内容,就像dict
一样。 documentation
答案 3 :(得分:0)
您正在尝试检查字符串是否在DateTimeIndex
中。 ind.strftime('%Y')
返回array(['2013', '2014'], dtype='|S4')
。
也许您的支票应该是:print('2013' in year.tolist())