【问题标题】:Evaluate datetime.date column with NoneType使用 NoneType 评估 datetime.date 列
【发布时间】:2018-02-13 19:55:32
【问题描述】:

我有一个从 pd.read-sql 查询创建的 pandas 列。该列中有空日期,它们以 NoneTypes 的形式返回,如下所示。

FFD
2014-10-29
2015-06-03
None
2017-05-05


print(type(stores['FFD'][0]))
class datetime.date
print(type(stores['FFD'][2]))
class'NoneType'

然后我尝试运行以下函数:

sixty = now - timedelta(60)
def f(row):
    if row['FFD'] < sixty:
        val = 'SR'
    return val

stores['JRSR'] = stores.apply(f, axis = 1)

这会返回一个错误:

TypeError: ("'<' not supported between instances of 'NoneType' and 'datetime.date'", 'occurred at index 10')

我可以将列转换为字符串,以便进行比较,但是我需要将此字段保留为日期字段以供下游使用。我的转换代码是:

stores['FFD'] = pd.to_datetime(stores['FFD'])
stores['FFD'] = stores['FFD'].dt.strftime("%Y-%m-%d")

如何在不转换列的情况下让我的函数工作?本质上,我希望我的函数只评估 datetime.date 对象。我试过了:

def(f)row:
    if isinstance(row['FFD'], NoneType):
         val = ""
    elif row['FFD'] < sixty:
         val = 'SR'

但这并没有按预期工作。

【问题讨论】:

  • 在您的第一个函数中,将 if row['FFD'] &lt; sixty: 更改为 if row['FFD'] and row['FFD'] &lt; sixty: 可能会有所帮助。在你的函数的第二个版本中,函数头有一个错字。将(f)row 更改为f(row)。
  • 哇 - 多么简单。只需从您的第一个建议中添加 and 就可以完美地工作。如果 row['FFD'] 和...做什么?
  • 哦,是的,谢谢!!!
  • Jason,我在下面的答案中添加了if row['FFD'] 的解释。

标签: python-3.x datetime comparison-operators


【解决方案1】:

在第一个f函数中,改变

if row['FFD'] &lt; sixty:

到

if row['FFD'] and row['FFD'] &lt; sixty:

解决了 OP 的问题。

如果row['FFD'] 包含除NoneType、0 或False 以外的任何内容,则if row['FFD'] 将评估为True。这是检查None 是否存在的Pythonic 方式。请注意,由于逻辑运算符的短路行为,检查 None 应始终放在复合条件的首位。所以if row['FFD'] and row['FFD'] &lt; sixty: 会起作用,但if row['FFD'] &lt; sixty and if row['FFD'] 不会。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    相关资源
    最近更新 更多