使用掩码设置numpy ndarray的值



我想计算两次之间的工作日,这两次都包含空值,下面是与计算工作日相关的问题。我已经发现,我使用掩码设置值的方式并不像预期的那样。

我使用的是python 2.7.11、pandas 0.18.1和numpy 1.11.0。我稍微修改过的代码:

import datetime
import numpy as np
import pandas as pd
def business_date_diff(start, end):
    mask = pd.notnull(start) & pd.notnull(end)
    start = start[mask]
    end = end[mask]
    start = start.values.astype('datetime64[D]')
    end = end.values.astype('datetime64[D]')
    result = np.empty(len(mask), dtype=float)
    result[mask] = np.busday_count(start, end)
    result[~mask] = np.nan
    return result

不幸的是,这并没有返回预期的工作日差异(相反,我得到了一些非常接近0的浮动)。当我检查np.busday_count(start, end)时,结果看起来是正确的。

print start[0:5]
print end[0:5]
print np.busday_count(start, end)[0:5]
# ['2016-07-04' '2016-07-04' '2016-07-04' '2016-07-04' '2016-07-04']
# ['2016-07-05' '2016-07-05' '2016-07-05' '2016-07-06' '2016-07-06']
# [1 1 1 2 2]

但当我检查results的值时,结果没有意义:

...
result = np.empty(len(mask), dtype=float)
result[mask] = np.busday_count(start, end)
result[~mask] = np.nan
print result
# [           nan               nan   1.43700866e-210   1.45159738e-210
# 1.45159738e-210   1.45159738e-210   1.45159738e-210   1.46618609e-210
# 1.45159738e-210   1.64491834e-210   1.45159738e-210   1.43700866e-210
# 1.43700866e-210   1.43700866e-210   1.43700866e-210   1.45159738e-210
# 1.43700866e-210   1.43700866e-210   1.43700866e-210   1.43700866e-210

我做错了什么?

您的问题是,对于您的numpy版本,您不能使用布尔数组作为数组的索引。只需使用np.where(mask==True)而不是掩码,使用np.where(mask==False)而不是~mask,它就会按需工作。

最新更新