【问题标题】:Python in operator not working as expected when comparing string and strftime values [duplicate]比较字符串和 strftime 值时,Python in 运算符未按预期工作[重复]
【发布时间】: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


【解决方案1】:

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

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

一种更 Pandorable 的方法是构造一个布尔序列,然后使用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()

【讨论】:

  • 这很令人困惑,不是吗?因为 list(series) 将返回不属于索引的元素列表..
  • @Tillus,是的,这是骗人的。在我看来,in 运营商应该检查值。要检查索引,最好使用inindex 属性。
  • 这对我有用.values。谢谢
【解决方案2】:

在您的第二个语句中,它检查索引号而不是列的值。如果要检查可以使用的值:

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

【讨论】:

    【解决方案3】:

    pandas.Series 上的in 检查索引中是否有内容,就像dict 一样。 documentation

    【讨论】:

    • 这很令人困惑,不是吗?因为 list(series) 将返回不属于索引的元素列表..
    【解决方案4】:

    您正在尝试检查字符串是否在 DateTimeIndex 中。 ind.strftime('%Y') 返回array(['2013', '2014'], dtype='|S4')

    也许你的支票应该是:print('2013' in year.tolist())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 2019-06-20
      • 2014-05-26
      • 2015-07-25
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多