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
测试这个的正确方法是什么?
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())
这种字典理解有助于提取带有 NaN 的字典(与
np.isnan(v)
不同,它会引发错误):
{k:v for k,v in my_dict.items() if v is np.nan}
然后,如果布尔信息足够,您可以检查结果字典的
len()
是否为正。