【问题标题】:python - check if nan float in dictionarypython - 检查 nan 是否在字典中浮动
【发布时间】:2018-03-04 07:38:02
【问题描述】:
import numpy as np
import pandas as pd
import tia.bbg.datamgr as dm
mgr = dm.BbgDataManager()

bb_yearb4 = "2016-12-30"
bb_today = "2017-09-22"

indices = [list of indices]
sids_index = mgr[indices]
df_idx = sids_index.get_historical('PX_LAST', bb_yearb4, bb_today)

nan = np.nan

price_test = {}
for index in indices:
    price_test["{0}".format(index)] = df_idx.loc[bb_today][index]

输出显示多个 nan float 值:

In [1]: price_test.values()
Out[1]: [nan, nan, nan, 47913.199999999997, nan, 1210.3299999999999, nan]

但是,对 nan 的测试显示错误:

In [2]: nan in price_test.values()
Out[2]: False

测试这个的正确方法是什么?

【问题讨论】:

  • np.nan in price_test.values()
  • @Wen:他们已经在这样做了,但它不起作用。

标签: python-2.7 pandas numpy dictionary nan


【解决方案1】:

NaN 很奇怪,因为 NaN != NaN。这是有充分理由的,但它仍然会破坏 in 检查以及假设正常 == 行为的所有其他内容。

使用特定于 NaN 的检查来检查 NaN,例如 numpy.isnan

any(np.isnan(val) for val in d.values())

或在非 NumPy 上下文中,

any(math.isnan(val) for val in d.values())

【讨论】:

  • 也许是math.isnan 而不是val != val
  • @JonClements:哦,是的。我忘了math 模块实际上有一个isnan
  • @piRSquared:他们的字典中的 NaN 与 np.nan 不是同一个对象。 Python 在== 之前执行is 检查,这让你失望。
猜你喜欢
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 2017-06-23
  • 2016-11-14
  • 2014-09-16
  • 2012-01-03
相关资源
最近更新 更多