python - 检查nan是否在字典中浮动

时间:2017-09-22 16:43:56

标签: python-2.7 pandas numpy dictionary nan

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浮点值:

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

测试此方法的正确方法是什么?

1 个答案:

答案 0 :(得分:9)

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())